Search code examples
c++constructorspecificationsconstructor-chaining

Constructor chaining in C++


My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then this process is called CONSTRUCTOR CHAINING , which is not supported in C++ . Recently I came across this paragraph while reading online material.... It goes like this ...

You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.

Does a member function calling the constructor also come under constructor chaining ?? Please throw some light on this topic in C++ .


Solution

  • The paragraph basically says this:

    class X
    {
       void Init(params) {/*common initing code here*/ }
       X(params1) { Init(someParams); /*custom code*/ } 
       X(params2) { Init(someOtherParams); /*custom code*/ } 
    };
    

    You cannot call a constructor from a member function either. It may seem to you that you've done it, but that's an illusion:

    class X
    {
    public:
        X(int i):i(i){}
        void f()
        {
           X(3); //this just creates a temprorary - doesn't call the ctor on this instance
        }
        int i;
    };
    
    int main()
    {
        using std::cout;
        X x(4);
        cout << x.i << "\n"; //prints 4
        x.f();
        cout << x.i << "\n"; //prints 4 again
    }