Can I call a constructor from another constructor (do constructor chaining) in C++?

 

Yes, in C++, you can call one constructor from another constructor of the same class using a feature called constructor chaining. This allows you to reuse initialization logic and avoid code duplication. This is particularly useful when you have multiple constructors with varying parameters but want to share common initialization steps.

Here's an example of how constructor chaining works in C++:

cpp
#include <iostream> using namespace std; class MyClass { public: MyClass() { cout << "Default constructor" << endl; } MyClass(int value) : MyClass() { // Calling the default constructor this->value = value; cout << "Parameterized constructor" << endl; } int getValue() const { return value; } private: int value; }; int main() { MyClass obj1; // Calls the default constructor MyClass obj2(42); // Calls the parameterized constructor cout << "Value of obj1: " << obj1.getValue() << endl; cout << "Value of obj2: " << obj2.getValue() << endl; return 0; }

In this example, MyClass has two constructors: a default constructor and a parameterized constructor that takes an integer argument. The parameterized constructor calls the default constructor using the constructor chaining mechanism.

When you create an object using the default constructor or the parameterized constructor, you can see the constructor chaining in action. The output of the program will be:

mathematica
Default constructor Default constructor Parameterized constructor Value of obj1: 0 Value of obj2: 42

As you can see, the default constructor is called first, followed by the parameterized constructor, which in turn calls the default constructor to initialize common parts of the object. This way, you can avoid repeating initialization logic and keep your code more maintainable.

Comments