Constructor delegation in C++11

C++11 added a feature that I personally find extremely useful. It is called constructor delegation. It is a natural addition to the language to reduce duplicated code in constructors of different signatures in a class. It can be understood easily with an example.

Consider a class with two constructors:

class Point
{
public:
    Point()
    {
        x_ = 0;
        y_ = 0;
        z_ = 0;
    }

    Point(int z)
    {
        x_ = 0;
        y_ = 0;
        z_ = z; // Only update z
    }

private:
    int x_;
    int y_;
    int z_;
};

How to avoid the duplicated initialization statements in both constructors? You should not call one constructor in the other constructor of the same class! That is a very common bug in C++, since that only creates a temporary object and does not actually call the constructor of the same object.

The common solution to this is to create an init function that is called from both constructors:

class Point
{
public:
    Point()
    {
        Init();
    }

    Point(int z)
    {
        Init();
        z_ = z; // Only update z
    }

private:
    void Init()
    {
        x_ = 0;
        y_ = 0;
        z_ = 0;
    }

    int x_;
    int y_;
    int z_;
};

C++11 constructor delegation provides an elegant solution that should have been there in C++ since the beginning: you can call a constructor by placing it in the initializer list of constructors. The above code with constructor delegation:

class Point
{
public:
    Point()
    {
        x_ = 0;
        y_ = 0;
        z_ = 0;
    }

    Point(int z) : Point()
    {
        z_ = z; // Only update z
    }

private:
    int x_;
    int y_;
    int z_;
};

If you are going to use constructor delegation, please remember to use a compiler version that supports it (I used GCC 5.1.0) and you may need to specify a C++11 flag (I used -std=c++11).

Reference: Sec 17.4.3 Delegating Constructors from The C++ Programming Language (4th Ed) by Stroustrup

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s