2.4.1 Delegated Constructors

What was the problem

Before C++11, constructors could not call other constructors. Consider the example below:

struct foo 
{ 
  foo(bar* b, float f, int i) 
    : m_bar(b), 
      m_f(f), 
      m_i(i) 
  {} 
 
  foo(bar* b, int i) 
    // can’t I call foo(b, 0, i) directly? 
    : m_bar(b), 
      m_f(0), 
      m_i(i) 
    {} 
 
private: 
  bar* const m_bar; 
  const float m_f 
  const int m_i; 
};

If we want to share initialization code between multiple constructors, then we have to put it in some separate member function called by the constructor, like this:

struct foo 
{ 
  foo(bar* b, float f, int i) 
  { 
    init(b, f, i); 
  } 
 
  foo(bar* b, int i) 
  { 
    init(b, 0, i); 
  } 
 
private: 
  void init(bar* b, float f, int i) 
  { 
    m_bar = b; 
    m_f = f; 
    m_i = i; 
  } 
 
  // We cannot make any of these members const anymore. 
  bar* m_bar; 
  float m_f; 
  int m_i; 
};

This approach was kind of error-prone. Stuff may happen before and after the call to the init() function, and actually nothing prevents it to be called at any point in the life of the instance. Finally, this is incompatible with const members.

How the Problem is Solved

Starting from C++11, a constructor can call another constructor:

struct foo 
{ 
  foo(bar* b, float f, int i) 
    : m_bar(b), 
      m_f(f), 
      m_i(i) 
  {} 
 
  foo(bar* b, int i) 
    : foo(b, 0, i) 
  {} 
 
private: 
  bar* const m_bar; 
  float m_f; 
  int m_i; 
};

This solves all problems.