Constructor Overloading in C++

Introduction

  • Constructors can be overloaded just like the member functions.
  • It is used to increase the flexibility of a class by having number of constructor for a single class.

Example : Program demonstrating the Constructor Overloading

#include <iostream>
using namespace std;
class OverloadConst
{
     public:
         int a;
         int b;
         OverloadConst()
         {
               a = b = 0;
         }
         OverloadConst(int c)
         {
               a = b = c;
         }
         OverloadConst(int a1, int b1)
         {
               a = a1;
               b = b1;
         }
};
int main()
{
     OverloadConst obj;
     OverloadConst obj1(10);
     OverloadConst obj2(20, 30);
     cout << "OverloadConst obj's a & b value : " <<
     obj.a << " , "<< obj.b << "\n";
     cout << "OverloadConst obj1's a & b value : "<<
    obj1.a << " ,"<< obj1.b << "\n";
    cout << "OverloadConst obj2's  a & b value : "<<
    obj2.a << " , "<< obj2.b << "\n";
    return 0;
}


Output:
OverloadConst obj's a & b value : 0 , 0
OverloadConst obj1's a & b value : 10 ,10
OverloadConst obj2's a & b value : 20 , 30

In the above example, the constructor OverloadConst is overloaded thrice with different initialized values.