- Learn C++ - https://www.learncpp.com -

11.7 — 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.

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 [1]

Show Solution [1]

Question #2


Why don’t we need to declare a constructor with no parameters in the program above, even though we’re constructing def without arguments?

Show Solution [1]


11.8 -- Overlapping and delegating constructors [2]
Index [3]
11.6 -- Constructor member initializer lists [4]