Calling constructor from constructor on C++ 11

In C++ 11 we can call constructor from another constructor inside the same class, this behavior is called Delegating constructors. This behavior is common on other modern language like C# but it’s not even allowed on C++ 03.

class Test {
    public Test() {
        DoSomething();
    }

    public Test(int count) : this() {
        DoSomethingWithCount(count);
    }

    public Test(int count, string name) : this(count) {
        DoSomethingWithName(name);
    }
}

Above is example on C# using this to call another constructor within same class, then on C++ 11 we can do it like this :

class Test {
    public:
    Test() {
        DoSomething();
    }

    Test(int count) : test() {
        DoSomethingWithCount(count);
    }

    Test(int count, string name) : test(count) {
        DoSomethingWithName(name);
    }
}

However to target C++ 11 is quite troublesome since some old compiler doesn’t have complete support. For example Visual Studio 2012 doesn’t support delegating constructor. So when porting new code to the old compiler, you need to slightly modify the code. The idea is to not using delegating constructor and using common initialization function instead .

class Test {
    private:
    void init() {
       DoSomething();
    }
    void init(int count) {
       DoSomethingWithCount(count)
    }
    public:
    Test() {
        init();
    }
    Test(int count){
        init(count);
    }

    Test(int count, string name){
        init(count);
        DoSomethingWithName(name);
    }
}

Look, now we call init function instead of calling constructor from other constructor, well it is not the best way to do it, but it’s acceptable since the modification is still minimal.

 

Update :

I found this article which does better on explaining this stuff .

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