Search

B.5 — Delegating constructors

Delegating constructors

In C++03, there are often cases where it would be useful for one constructor to call another constructor in the same class. Unfortunately, this is disallowed by C++03. Commonly this ends up resulting in either duplicated code:

(where the code to do A is defined twice)

or use of an init() non-constructor function to keep the common code accessible to both constructors that need it:

While using the init() method is considered better practice than duplicating code, it has a couple of downsides. First, it’s not quite as readable, as it adds a new function and several new function calls. Second, because InitA() is not a constructor, it can be called during the normal program flow, where member variables may already be set and dynamically allocated memory may already be allocated. This means InitA() needs to be additionally complex in order to handle both the new initialization and reinitialization cases properly.

Fortunately, C++11 adds the ability to chain constructors together (called delegating constructors)

As you can see, it’s much cleaner.

One thing to note: You should always use the initialization list syntax when delegating constructors, as compilers that do not support delegating constructors will generally flag this as a compiler error. If you try to call one constructor from the body of another constructor, the compiler will not complain and your program may also not behave as expected.

B.6 -- New virtual function controls (override, final, default, and delete)
Index
B.4 -- Initializer lists and uniform initialization

5 comments to B.5 — Delegating constructors

  • Ganesh Koli

    Hi Alex, Thank you for the article.
    How this will work in inheritance ? and want to initialize super class members as well?

    Class Derive : public B

    It is not allowing the other member initialization with delegate constructor.
    I think this restriction to avoid below situation :

    Class Derive : public Base
    {
      int size;
    public :
      Derive () : Base () {}
      Derive (int s) : Base(s), Derive() {}   // compilation error
    }

    In above code if no compilation allow it then Base class constructor called two times ?

    Please correct me , if i am wrong or understood it wrongly .

  • class Calc
    {
    private:
        int m_nValue;

    public:
        Calc() { m_nValue = 0; }

        void Add(int nValue) { m_nValue += nValue; }
        void Sub(int nValue) { m_nValue -= nValue; }
        void Mult(int nValue) { m_nValue *= nValue; }

        int GetValue() { return m_nValue; }
    };

  • waleed.9

    Hi
    please I need an answre to this Q
    Write a program to convert Yard to meters by reading the input from a file and write the output to another file.
    !yard=0.9114 kilometer

Leave a Comment

Put all code inside code tags: [code]your code here[/code]