Search

8.6 — Overlapping and delegating constructors

Constructors with overlapping functionality

When you instantiate a new object, the object’s constructor is called implicitly by the C++ compiler. It’s not uncommon to have a class with multiple constructors that have overlapping functionality. Consider the following class:

This class has two constructors: a default constructor, and a constructor that takes an integer. Because the “code to do A” portion of the constructor is required by both constructors, the code is duplicated in each constructor.

As you’ve (hopefully) learned by now, having duplicate code is something to be avoided as much as possible, so let’s take a look at some ways to address this.

The obvious solution doesn’t work prior to C++11

The obvious solution would be to have the Foo(int) constructor call the Foo() constructor to do the A portion.

or

However, with a pre-C++11 compiler, if you try to have one constructor call another constructor, it will often compile, but it will not work as you expect, and you will likely spend a long time trying to figure out why, even with a debugger.

(Optional explanation: Prior to C++11, calling a constructor explicitly from another constructor creates a temporary object, initializes the temporary object using the constructor, and then discards it, leaving your original object unchanged)

Using a separate function

Constructors are allowed to call non-constructor functions in the class. Just be careful that any members the non-constructor function uses have already been initialized. Although you may be tempted to copy code from the first constructor into the second constructor, having duplicate code makes your class harder to understand and more burdensome to maintain. The best solution to this issue is to create a non-constructor function that does the common initialization, and have both constructors call that function.

Given this, we can change the above class to the following:

In this way, code duplication is kept to a minimum.

Relatedly, 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. However, trying to call a constructor directly will generally result in unexpected behavior. Many developers simply copy the code from the constructor in your initialization 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:

It is fairly common to include an Init() function that initializes member variables to their default values, and then have each constructor call that Init() function before doing its parameter-specific tasks. This minimizes code duplication and allows you to explicitly call Init() from wherever you like.

One small caveat: be careful when using Init() functions and dynamically allocated memory. Because Init() functions can be called by anyone at any time, dynamically allocated memory may or may not have already been allocated when Init() is called. Be careful to handle this situation appropriately -- it can be slightly confusing, since a non-null pointer could be either dynamically allocated memory or an uninitialized pointer!

Delegating constructors in C++11

Starting with C++11, constructors are now allowed to call other constructors. This process is called delegating constructors (or constructor chaining).

To have one constructor call another, simply call the constructor in the member initializer list. This is one case where calling another constructor directly is acceptable. Applied to our example above:

This works exactly as you’d expect. Make sure you’re calling the constructor from the member initializer list, not in the body of the constructor.

Here’s another example of using delegating constructor to reduce redundant code:

This class has 2 constructors, one of which delegates to Employee(int, const std::string &). In this way, the amount of redundant code is minimized (we only have to write one constructor body instead of two).

A few additional notes about delegating constructors. First, a constructor that delegates to another constructor is not allowed to do any member initialization itself. So your constructors can delegate or initialize, but not both.

Second, it’s possible for one constructor to delegate to another constructor, which delegates back to the first constructor. This forms an infinite loop, and will cause your program to run out of stack space and crash. You can avoid this by ensuring all of your constructors resolve to a non-delegating constructor.

8.7 -- Destructors
Index
8.5b -- Non-static member initialization

104 comments to 8.6 — Overlapping and delegating constructors

  • Nguyen

    Hi,

    I expected to see my output shown as following:
    Employee Alex created.

    But there is no output at all?  Please help.

  • 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 compilation allow it then Base class constructor could called two times ? (or something danger)

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

  • Jeffrey Liu

    Hi,

    When using a non-constructor function to avoid duplicate code, would this not lead to certain issues (the same as the ones given when not using a member initializer list) because they are assigning values to the member variables, and not actually initializing them?

    Thank you!

  • Dany

    Hello. Can someone clarify which syntax should i prefer upon creation of object (i think {} because we can distinguish initialization from assignment and function call)
    and upon creation of delegating constructor (here i am really confused why both versions are available). Thanks in advance.

    • It's not just the syntax that's different, the 2 forms can do different things.
      Both are direct initialization, but brace initialization (curly braces) enforces stricter type checks and can be used to initialize lists or default-initialize.
      Use brace initialization unless you're constructing a type which has a list constructor and you want to use a non-list constructor.

  • Yaroslav

    (Optional explanation: Prior to C++11, calling a constructor explicitly from another constructor creates a temporary object, initializes the temporary object using the constructor, and then discards it, leaving your original object unchanged)

    May be it will be better to rewrite this because for me (for a noob) it was not clear at all what's going on.

    may be something like:
    prior to c++11 there was no member initializing list so we can't use it then.
    and if we will try to call the first constructor from a body of another constructor it will not call it, it will just simply create another instance of a class (in a form of anonymous object, you will learn it in ...), then it will initialize that copy/instance with the first constructor, and then discard it, leaving our original object unchanged.

  • Alireza

    Hi,
    Why can't I do this way:

    Causes an error:

    What does it mean ?

    • If you delegate construction to another constructor, that constructor call must be the only thing in the constructor initializer list. There can be no other initializations or constructor calls.
      Once you call a constructor, the object is considered initialized. Since an object can only be initialized once, you can't initialize anything else (eg. by calling more constructors).
      Initialize `m_color` and `m_radius` directly.

  • Tommy

    I'm failing to understand your employee example. The delegating constructor (ie. the extension, right?), it looks redundant because it's not adding any new functionality. It seems like it has less functionality actually. Have I missed something? How is the first constructor not enough?

    • Alex

      The first constructor won't let you create Employee("Alex").

      It's not a wonderful example because this could be solved trivially by flipping the order of the id and string fields, but it does at least show the mechanics.

  • NXPY

    When using a seperate function , isn't it better to make it inline to reduce time ?

Leave a Comment

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