Delegating Constructors in C++ 11

Sometimes it is useful for a constructor to be able to call another constructor of the same class. This process is called delegating constructors (or constructor chaining).

There is one case i.e. calling the another constructor in member initialize list, which is acceptable.

An example without delegation:-

class fun
{
	int x, y, z;
public:
	fun()
	{
		x = 0;
y = 0;
z = 0;
	}

	fun(int val)
	{
		x = 0; y = 0;		//// This line is redundant  
		z = val;
	}

	void showValues()
	{
		cout << x << "  "<< y << "  "<< z;
	}
};

void delegatingConstructorExample()
{
	fun f(3);
	f.showValues();
}

OutPut:

0  0  3

Solving above redundant code problem using init()

In above solution, there is two line of code common in both constructor, leading to code duplication/redundant code. One solution to avoid this situation would have been the creation of an init function that can be called from both the constructors

class fun
{
	int x, y, z;

	void init()
	{
		x = 0, y = 0;
	}
public:
	fun()
	{
		init();
z = 0;
	}

	fun(int val)
	{
		init();
		z = val;
	}

	void showValues()
	{
		cout << x << "  "<< y << "  "<< z;
	}
};

void delegatingConstructorExample()
{
	fun f(3);
	f.showValues();
}

Solving above redundant code problem using delegation constructor()

While the usage of an init() function eliminates duplicate code, it still has its own drawbacks.

  • It’s not quite as readable, as it adds a new function and several new function calls within constructor.
  • Be careful when using init() and dynamically allocation members of class. Because init() can be call by anyone at any time, dynamically allocated memory may or may not have already been allocated when Init() is called.
class fun
{
	int *x, y, z;

	void init()
	{
		*x = 0;	//crash the program here
y = 0;
	}
public:
	fun()
	{
		init();	
		x = new int();
z = 0;
	}

	fun(int val)
	{
		init();
		x = new int();
		z = val;
	}

	void showValues()
	{
		cout << *x << "  "<< y << "  "<< z;
	}
};
      	void delegatingConstructorExample()
{
	fun f(3);
	f.showValues();
}

Solving above redundant code problem using Delegating Constructor

C++ Constructor delegation provides an elegant solution to handle this problem, by allowing us to call a constructor by placing it in the initializer list of other constructors.

e.g.

class fun
{
	int x, y, z;

public:
	fun()
	{
		x = 0; y = 0; z = 0;
	}

	fun(int val):fun()
	{
		z = val;
	}

	void showValues()
	{
		cout << x << "  "<< y << "  "<< z;
	}
};

void delegatingConstructorExample()
{
	fun f(3);
	f.showValues();
}

Note that call the fun() constructor inside the fun(int vale), it will not work as you expect. What’s happening is that fun(); instantiate a new fun object, which is immediately discarded, because it’s not stored in a variable.

i.e

fun(int val)
{
	fun(); 		//error new object created and destroyed immediately.
z = val;
}

  • 23
    Shares