Search

Enter your search terms

Submit search form

B.5 — Delegating constructors

By Alex on November 27th, 2011 | last modified by Alex on November 27th, 2011

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

classFoo

{

public:

Foo()

{

// code to do A

}

Foo(intnValue)

{

// code to do A

// code to do B

}

};

(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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

classFoo

{

public:

Foo()

{

InitA();

}

Foo(intnValue)

{

InitA();

// code to do B

}

voidInitA()

{

// code to do A

}

};

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.

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.