C++ Delegating Constructors

Delegating constructors are a C++11 feature that allows a constructor to call another constructor of the same class to initialize its members. This can be useful to avoid code duplication when you have multiple constructors that share the same initialization code.

Here's an example of a class with two constructors, where the second constructor delegates to the first constructor to do the initialization:

class MyClass {
  public:
    int myInt;
    MyClass() : MyClass(0) {
    }
    MyClass(int value) {
      myInt = value;
    }
};
So‮ecru‬:www.theitroad.com

In this example, the first constructor delegates to the second constructor to initialize myInt with a default value of 0. The second constructor initializes myInt with the value provided as an argument.

You can create an object of the MyClass class using either of the constructors like this:

MyClass obj1; // Uses the first constructor
MyClass obj2(42); // Uses the second constructor

In the first example, the first constructor is called, which delegates to the second constructor to initialize myInt with a default value of 0. The value of myInt in the obj1 object is initialized to 0.

In the second example, the second constructor is called, which initializes myInt with the value of 42. The value of myInt in the obj2 object is initialized to 42.

Note that the constructor that delegates to another constructor must be a member initializer and can only call a constructor of the same class. Delegating constructors cannot be used to call a constructor of a base class.

Delegating constructors can help you reduce code duplication and make your code more maintainable. However, they should be used with care, as they can lead to more complex code and make it harder to understand the initialization logic of a class.