Constructor Overloading in C++

constructor overloading

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.

Implementation for Constructor Overloading

#include <iostream>
using namespace std;
class Demo
{
  int x, y;
  public:
    Demo()
    {
       x = 0;
       y = 0;
    }
    Demo(int x1, int y1)
    {
      x = x1;
      y = y1;
    }
    Demo(int x1)
    {
     x = x1;
     y = x1;
    }

    void print()
    {
    cout<<"\nValues are : "<<x<<" and "<<y ;
    }
};

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

  d1.print();
  d2.print();
  d3.print();
  return 0;
}
Output –
Values are : 0 and 0
Values are : 10 and 20
Values are : 10 and 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.