Constructor Delegation in C++


Here we will see what is the constructor delegation? When a constructor calls other constructor of the same class, then it is called the constructor delegation. This feature is present from C++11.

Let us see the following program, and try to analyze what are the difficulties in this code.

Example

#include <iostream>
using namespace std;
class MyClass {
   int a, b, c;
   public:
   MyClass(){
      a = b = c = 0;
   }
   MyClass(int c) {
      // Initializing a and b are redundent, only c initialization is needed here
      a = 0;
      b = 0;
      this->c = c;
   }
   void display(){
      cout << "a : " << a << ", b : " << b << ", c : " << c;
   }
};
main() {
   MyClass my_obj(5);
   my_obj.display();
}

Output

a : 0, b : 0, c : 5

Here we can see that the code is working fine, but there is some redundant code. The non-parameterized constructor can set the values of a and b to 1. So if we use the first constructor into the second one, then it will be more effective. For this reason, we have to use the method called constructor delegation.

Example

#include <iostream>
using namespace std;
class MyClass {
   int a, b, c;
   public:
   MyClass(){
      a = b = c = 0;
   }
   MyClass(int c) : MyClass(){ //using constructor delegation
      this->c = c;
   }
   void display(){
      cout << "a : " << a << ", b : " << b << ", c : " << c;
   }
};
main() {
   MyClass my_obj(5);
   my_obj.display();
}

Output

a : 0, b : 0, c : 5

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements