Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

In C++, constructor overloading refers to the practice of defining multiple constructors for a class, each with a different signature. A constructor is a special member function that gets called automatically when an object of the class is created.

Here's an example of constructor overloading:

class MyClass {
public:
    MyClass() {
        // default constructor
    }
    
    MyClass(int arg1) {
        // constructor with one argument
    }
    
    MyClass(int arg1, int arg2) {
        // constructor with two arguments
    }
};

In this example, we have defined three different constructors for the MyClass class. The first constructor is the default constructor, which takes no arguments. The second constructor takes one argument of type int, and the third constructor takes two arguments of type int.

When we create an object of the MyClass class, we can use any of these constructors to initialize the object, depending on the arguments that we pass. For example:

MyClass obj1;         // calls the default constructor
MyClass obj2(42);     // calls the constructor with one argument
MyClass obj3(1, 2);   // calls the constructor with two arguments

Constructor overloading is useful when you want to provide different ways of initializing objects of your class. By defining multiple constructors, you can provide flexibility to users of your class and make it easier for them to create objects that suit their needs.

  • No labels