Constructor Overloading in C++

constructor overloading

C++ Constructor Overloading

Constructor Overloading in C++ is similar to Function Overloading, we can define more than one constructors for a class. It is defined by naming the constructor same as the name of the 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.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription