Constructor Overloading in C++

C++ Constructor Overloading

Constructor Overloading is similar to Function Overloading, we can define more than one Constructors for a class, the following are necessary conditions for the same –

  • Name of constructor should be same as the name of the class
  • The parameters passed in each variation of constructor should be different example –
    • Demo(int x) and Demo(int x, int y)
  • Constructors are basically special functions of the class itself.

We recommend reading our post on Constructors here first.

Constructor Overloading in C++

Implementation for Constructor Overloading

#include <iostream>
using namespace std;

class Demo
int x, y;
x = 0;
y = 0;
Demo(int x1, int y1)
x = x1;
y = y1;
Demo(int x1)
x = x1;
y = x1;

void print()
cout<<"Values are : " <<x << "and "<< y <<endl;

int main()
Demo d1;
Demo d2(10,20);
Demo d3(10);

return 0;

Output –

Values are : 0and 0

Values are : 10and 20

Values are : 10and 10

In the above example, depending upon the parameters passed( similar as function overloading), the appropriate constructor was called, this is the basic functionality of constructor overloading.