Constructor Delegation in C++

Hi guys, today we will talk about Constructor Delegation in C++.

When a constructor calls another constructor of the same class, it is called constructor delegation.

Constructor Delegation in C++

Now, let us see an example in which we are calculating the sum of 3 numbers without using delegation.

#include<bits/stdc++.h>
using namespace std;
class sum
{
    int a,b,c;
public:
    sum()           // Constructor 1
    {
        a=100;
        b=200;
        c=300;
    }
    sum(int z)     // Constructor 2
    {
        c=z;
    }
    void print()
    {
        cout<<"sum= "<<a+b+c;
    }
};
int main()
{
    sum obj(500);
    obj.print();
}

The output of this code will show some random value. This is because when we create an object, it will move to the constructor 2 and not the constructor 1. And hence, the value of variable a and b will be garbage value.

So, to solve this problem, we have 2 methods i.e. either we declare both and b in the constructor 2 or we can use delegation.

Now, let us try to solve in both the ways.

Method 1:

#include<bits/stdc++.h>
using namespace std;
class sum
{
    int a,b,c;
public:
    void dec()
    {
        a=100;
        b=200;
    }
    sum(int z)
    {
        c=z;
        dec();
    }
    void print()
    {
        cout<<"sum= "<<a+b+c;
    }
};
int main()
{
    sum obj(500);
    obj.print();
}

In this case, the output will be correct i.e.

sum= 800

This is because I have created a function dec() which will initialize the variable a and b with the value 100 and 200 respectively.

Method 2: Using delegation

#include<bits/stdc++.h>
using namespace std;
class sum
{
    int a,b,c;
public:
    sum()
    {
        a=100;
        b=200;
        c=300;
    }
    sum(int z): sum()           // Constructor Delegation
    {
        c=z;
    }
    void print()
    {
        cout<<"sum= "<<a+b+c;
    }
};
int main()
{
    sum obj(500);
    obj.print();
}

This is the delegation method in which a parameterized constructor is calling the default constructor before executing itself.
Hence, the value of the variable a,b,c will be 100, 200, 300 respectively in the beginning. When the parameterized constructor is executing, the value of variable c will be updated to 500 and hence correct output will be shown.

Output:

sum= 800

We should avoid this method because it creates another object of the same class and hence increases the space complexity of the code.

Leave a Reply

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