Delegating Constructors

In some situations, it’s useful to provide more than one way to initialise an object. When we choose to provide more than one constructor, we want to avoid having to duplicate code.

Consider the following example of a simple 2D vector class, which can be initialised either by passing in two doubles, or a double array.

class Vector
{
private:
    double _x, _y, _magnitude;

public:
    Vector(double x, double y)
    {
	    _x = x;
	    _y = y;
	    _magnitude = sqrt(x * x + y * y);
    }

    Vector(double *v)
    {
        _x = v[0];
        _y = v[1];
        _magnitude = sqrt(x * x + y * y);
    }
};

Here, the code to calculate the magnitude of the vector is duplicated. In C++03, the usual approach to avoid this is to have an init() function which can be called from both constructors. However, C++11 allows us to directly call one constructor from another.

Using this feature, we could replace the second constructor with the following:

Vector(double *v) : Vector(v[0], v[1])
{
}

That’s all we need! This offers a very concise way to implement multiple constructors without having to duplicate code.