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)
B.4 -- Initializer lists and uniform initialization

3 comments to B.5 — Delegating constructors

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">