In this tutorial, we will learn constructor overloading in C++ with the help of examples.

What is Constructor Overloading?

When more than one constructor of a class has different numbers or types of arguments, then the constructors are said to be overloaded.

class MyClass{
    int num;
    
    public:
    MyClass(){
        num = 0;
    }
    
    MyClass(int x){
        num = x;    
    }
};

Here, MyClass has two contructors with different function signatures.

Which of these two constructors will be called depends on the object initialization statement of class MyClass.

For instance, in the following program, we are creating and intializing object by passing integer to the class as MyClass obj = MyClass(7).

// Online C++ compiler to run C++ program online
#include <iostream>
class MyClass{
    int num;
    public:
    
    /* will be called when no argument is 
    passed at time of object creation */
    MyClass(){
        num = -1;
    }
    
    /* will be called when an integer is
    passed at the time of object creation */
    MyClass(int x){
        num = x;    
    }
    
    void display(){
        std::cout << "Number: " << num;
    }
};


int main() {
    MyClass obj = MyClass(7);
    obj.display();

    return 0;
}

Output:

Number: 7

If we do not pass any integer to the class during the object creation (i.e. MyClass obj = MyClass()), then the non-parametrized constructor will be invoked.

...

int main() {
    MyClass obj = MyClass();
    obj.display();

    return 0;
}

Output:

Number: -1

The decision of which constructor to call is done by the compiler during the compile time. This phenomenon is also known as static polymorphism.

When to use Constructor Overloading in C++?

Overloading constructors makes a class more flexible for object creation.

So, when we want a class to allow different ways to initialize its objects, we should use constructor overloading in C++.

Leave a Reply