Simple Example Program For Constructor Overloading In C++


C++ allows us to use a default constructor and a parameterized constructor in the same class. One constructor does not accept any arguments and the other constructor accepts arguments. Hence, it is possible to have more than one constructor with the same name but different argument list. Depending on the manner in which the object is initialized, the corresponding constructor is invoked.

Simple Example Program For Constructor Overloading In C++

#include<iostream> using namespace std; class MyPack{ int a; public: MyPack(){ cout<<"Default constructor called"<<endl; a=10; } MyPack(int x){ cout<<"One - argument parameterized constructor called"<<endl; a = x; } void print(){ cout<<"The value of a is :"<<a<<endl; } }; int main(){ MyPack s1(8); //Way to call an overloaded constructor MyPack s2; s1.print(); s2.print(); return 0; }

Output:-

One - argument parameterized constructor called
Default constructor called
The value of a is :8
The value of a is :10

Explanation of the program

In this program, the class MyPack has 2 constructors - one is default constructor and other is parameterized constructor which accepts one argument. While object s1 and s2 are initialized, s1 passes an argument whereas s2 does not pass any argument. Hence when s1 is created, the parameterized constructor is invoked. When s2 is created, the default constructor is invoked.