Constructor Delegation

In this lesson, we will further build on the idea of an initializer list in a constructor.

We'll cover the following

So far, we’ve seen how class members can be initialized in the constructor through an initializer list. However, we are not restricted to just that.

Definition #

Constructor delegation occurs when a constructor calls another constructor of the same class in its initializer list.

struct Account{
  Account(): Account(0.0){}
  Account (double b): balance(b){} };

In the example above, the default constructor calls the parameterized constructor and initializes balance to 0.0.

Rules #

  • When the constructor call in the initializer list is completed, the object is created. This object can then be altered in the calling constructor’s body.

  • It is important to perform constructor delegation in the initializer list. If it is called in the body, a new class object will be created and we will end up with two objects, which is not the behavior we want.

  • Recursively invoking constructors will result in undefined behavior.

The aim of delegation is to let one constructor handle initialization. That object can be used or modified by all other constructors. In other words, constructors can delegate the task of object creation to other constructors.

A great advantage of constructor delegation is that the initialization code is localized. Once that code has been tested, the rest of the code can be built upon it robustly. Also, bugs, if there are any, will be localized to the specific constructor(s) instead of being spread around all over the place.

Example #

Get hands-on with 1200+ tech skills courses.