Delegating Constructors in C++
Since C++11, a constructor can delegate its work to another constructor of the same class. This is the modern way in C++ to put common actions for all constructors in one constructor. In C++ code before C++11, you often used an init function for such a task.
class Degree{ int degree; public: Degree(int deg){ // (1) degree= deg % 360; if (degree < 0) degree += 360; } Degree(): Degree(0){} // (2) Degree(double deg): Degree(static_cast(ceil(deg))){} // (3) };
The constructors (2) and (3) of the class Degree delegate all its initialization work to the constructor (1), which verifies its arguments. Invoking constructors recursively is undefined behavior.