What is the advantage of using initializers for a constructor in C++?

c++

Solution

All members are initialised before entering the body of the constructor. If you don't provide an initialiser in the init list, then they're default constructed.

In your first example the following happens:

- `theRadius` is initialised to 1.0

In your second example the following happens:

- `theRadius` is initialised

- 1.0 is copied to `theRadius`

With simple types like ints and floats this won't matter much. however if your members are objects with non-trivial constructors / copy constructors then it's a lot more efficient to use the initialisation list approach.

Problem

``` Sphere() : theRadius(1.0) { } ``` Why is it preferable to have a constructor written with initializers (above) than a constructor that initializes the data members within its body (below)? ``` Sphere() { theRadius = 1.0; } ```

Original source