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.

Constructor Overloading in C++

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 page on Constructors here first.

Implementation for Constructor Overloading

Run
#include <iostream> 
using namespace std;

class MyClass {
    private:
        int x, y;
    
    public:
        MyClass() {
            x = 0;
            y = 0;
        }
        
        MyClass(int a) {
            x = a;
            y = 0;
        }
        
        MyClass(int a, int b) {
            x = a;
            y = b;
        }
        
        void print() {
            std::cout << "x = " << x << ", y = " << y << std::endl;
        }
};

int main() {
    MyClass obj1;
    MyClass obj2(5);
    MyClass obj3(3, 7);
    
    obj1.print();
    obj2.print();
    obj3.print();
    
    return 0;
}

Output -

x = 0, y = 0
x = 5, y = 0
x = 3, y = 7
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