Tuesday, November 12, 2013

What is Delegating Constructor in C++?

Ahh... It has been so long I didn’t write any C++ code since 2010. While I was reading C++ article published at IBM’s website, I come across this term which I found very interesting and new to me. Consider following code snippet, all constructors use as a common initializer for its member variable.
class ClsA {
    private:
        int var;
        
    public:
        ClsA() : var(0) {}
        ClsA(int x) : var(x) {}
        
        ...
}
This is what I usually did at old school. Now there is slightly little improvement on the constructor syntax. Remember how the syntax applied when a member variable is initialized by a constructor. The same syntax can be applied to trigger another constructor to perform member variable initialization. This is what the syntax called delegating constructor. Consider:
class ClsA {
    private:
        int var;
        
    public:
        ClsA() : ClsA(123) {}    // (1)
        ClsA(int x) : var(x) {}  // (2)
        
        ...
};
When I do this:

ClsA clsA;

The constructor at (1) will get invoke and further call another constructor at (2) where member variable var get initialize to 123. The constructor at (1) is a delegating constructor, (2) is a target constructor. Somehow programmer still has the flexibility to invoke constructor at (2) directly to perform its initialization. More details on this specification can be found at open-std(dot)org.

No comments: