A constructor can delegate some responsibilities (of member initialization) to another constructor of the same class type. This is called constructor chaining process and that constructor is called delegating constructor.
A constructor delegate initialization to another by using them in member initialization list. For example,
#include <iostream>
class Point
{
int m_x{};
int m_y{};
int m_z{};
public:
Point() = default;
Point(int x, int y)
: Point{x, y, 0}
{
std::cout << "Constructing using Point(x, y)\n";
}
Point(int x, int y, int z)
: m_x{x}, m_y{y}, m_z{z}
{
std::cout << "Constructing using Point(x, y, z)\n";
}
void print() const
{
std::cout << "{" << m_x << ", " << m_y << ", " << m_z << "}\n";
}
};
int main(int argc, char const *argv[])
{
Point{}.print();
Point{1, 2}.print();
Point{1, 2, 3}.print();
return 0;
}Constructor Point(x, y) is delegating the initializations to constructor Point(x, y, z) by providing value 0 to z parameter.
One thing to remember is that the constructor which is delegating to another constructor is not allowed to do member initialization. For example,
class Point
{
int m_x{};
int m_y{};
int m_z{};
public:
Point() = default;
Point(int x, int y)
: m_x{x}, m_y{y}
{
std::cout << "Constructing using Point(x, y)\n";
}
Point(int x, int y, int z)
: Point{x, y}, m_z{z} // not allowed. it'll fail.
{
std::cout << "Constructing using Point(x, y, z)\n";
}
void print() const
{
std::cout << "{" << m_x << ", " << m_y << "}\n";
}
};This type of delegation is not allowed and will fail the compilation process.
Note
And thus we need to go with delegating from less parameters constructors to more parameter constructors as shown in above examples. We delegate from
Point(x,y)toPoint(x, y, z), instead of other way round.