Search

8.5b — Non-static member initialization

When writing a class that has multiple constructors (which is most of them), having to specify default values for all members in each constructor results in redundant code. If you update the default value for a member, you need to touch each constructor.

Starting with C++11, it’s possible to give normal class member variables (those that don’t use the static keyword) a default initialization value directly:

This program produces the result:

length: 1.0, width: 1.0

Non-static member initialization (also called in-class member initializers) provides default values for your member variables that your constructors will use if the constructors do not provide initialization values for the members themselves (via the member initialization list).

However, note that constructors still determine what kind of objects may be created. Consider the following case:

Even though we’ve provided default values for all members, no default constructor has been provided, so we are unable to create Rectangle objects with no arguments.

If a default initialization value is provided and the constructor initializes the member via the member initializer list, the member initializer list will take precedence. The following example shows this:

This prints:

length: 2.0, width: 3.0
length: 4.0, width: 1.0

Note that initializing members using non-static member initialization requires using either an equals sign, or a brace (uniform) initializer -- the direct initialization form doesn’t work here.

Rule

Favor use of non-static member initialization to give default values for your member variables.

Quiz time

Question #1


Update the following program to use non-static member initialization and member initializer lists.

This program should produce the result:

color: black, radius: 10
color: blue, radius: 10
color: black, radius: 20
color: blue, radius: 20

Show Hint

Show Solution

Question #2


Why do we not need to declare a default constructor in the program above, even though we’re constructing def without arguments?

Show Solution


8.6 -- Overlapping and delegating constructors
Index
8.5a -- Constructor member initializer lists

92 comments to 8.5b — Non-static member initialization

  • John

    I have a question about Question 2. Isn't the second Ball constructor the default constructor? In 8.5, a default constructor was defined as "a constructor that takes no parameters (or has parameters that all have default values)." The second constructor has parameters that all have default values, so wouldn't it be the default constructor?

  • Hjw

    'Note that initializing members using non-static member initialization requires using either an equals sign, or a brace (uniform) initializer -- the direct initialization form doesn’t work here.'

    Don't you mean the opposite? All code above uses direct initialization {}?

Leave a Comment

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