C++ 11 feature: Delegating constructor

Delegating constructor is a new concept in C++ 11.

Why we need delegating constructor?

1. Delegating constructor is used to prevent code duplication.

2. It is the only way to delegate the initialization list

3. Consider the code below:

#include <iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com

using namespace std;

class MyClass 
{ 
    int a;
    int b; 
    int c;
    
public:
    MyClass()
    {
        a = 0;
        b = 0;
        c = 0;
    }
    
    MyClass(int c)
    {
        a = 0;
        b = 0;
        this->c = c;
    }
}; 
  

int main() 
{ 
    MyClass obj;
} 

If you see the default constructor and parameterized constructor. We are doing the smae task “a = 0; b = 0;”. But we are only changing “this->c = c;”. We are doing code deuplication.

One thing you can do is, you can create a common function init(), then it can be called from both the constructor as shown below:

#include <iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com

using namespace std;

class MyClass 
{ 
    int a;
    int b; 
    int c;
    
public:
    void init()
    {
        a = 0;
        b = 0;
        c = 0;
    }
    
    MyClass()
    {
        init();
    }    
    
    MyClass(int c)
    {
        init();
        this->c = c;
    }
}; 
  

int main() 
{ 
    MyClass obj;
} 

But with C++ 11 will provide a more elegant solution. You can use constructor delegation.

#include <iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com

using namespace std;

class MyClass 
{ 
    int a;
    int b; 
    int c;
    
public:
    MyClass()
    {
        a = 0;
        b = 0;
        c = 0;
    }
    
    // Constructor delegation  
    MyClass(int c): MyClass()
    {
        this->c = c;
    }
}; 
  

int main() 
{ 
    MyClass obj;
} 
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *