C++11 What is Delegating Constructors?

Delegating constructors are a feature introduced in C++11 that allows one constructor of a class to call another constructor of the same class to initialize the object. This feature simplifies code and eliminates the need to repeat the same code multiple times for different constructors.

A delegating constructor has the same syntax as a regular constructor, but it calls another constructor of the same class in its member initializer list using the this keyword. Here's an example:

class MyClass {
public:
    MyClass(int x, int y) : x_(x), y_(y) {}
    MyClass(int x) : MyClass(x, 0) {} // delegating constructor
private:
    int x_;  int y_;
};
In this example, the MyClass has two constructors: one that takes two int parameters and one that takes one int parameter. The second constructor is a delegating constructor because it calls the first constructor using this. The x parameter is passed to the first constructor, and the y parameter is set to zero. Delegating constructors can also call other constructors of the same class that are not the default constructor. Here's an example:

class MyClass {
public:
  MyClass(int x, int y) : x_(x), y_(y) {}
  MyClass(int x) : MyClass(x, 0) {}
  MyClass() : MyClass(0) {}  // delegating constructor
private:
  int x_;
  int y_;
};
In this example, the MyClass has three constructors: one that takes two int parameters, one that takes one int parameter, and one that takes no parameters. The third constructor is a delegating constructor that calls the second constructor with a default value for x. Delegating constructors can also be used to perform additional initialization after calling another constructor. Here's an example:

class MyClass {
public:
  MyClass(int x, int y) : x_(x), y_(y) {}
  MyClass(int x) : MyClass(x, 0) {}
  MyClass() : MyClass(0) {
    z_ = 0;
  }
private:
  int x_;
  int y_;
  int z_;
};
In this example, the third constructor is a delegating constructor that calls the second constructor with a default value for x, and then initializes the z_ member variable to zero.

Comments

Popular posts from this blog

C++ data structure and containers and their operation with time complexity

Copyable and non-copyable Objects in C++

Prepare for your next C++ interview