Const member init

Viewed 91

In my book "The C++ Programming Language" Bjarne Stroustrup I'm read about const members init and saw the next code (i change var names and values):

class ConstMembers
{
public:
    static const int a = 1; // ok
    static int b = 2; // error: non const
    const int c = 3; // error: no static
    static const float d = 2.3; // error: not integer
};

But when i run this code in Clion 2020.1 with next cmake setting

set(CMAKE_CXX_STANDARD 11)  

in third case

const int c = 3; // error: no static 

i didn't get an error.

clion screen

It is an error in the book or the c++11 allows such initialization?

2 Answers

Yes, default initializer list was supported since C++11.

(emphasis mine)

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.

You can also initialize it as

class ConstMembers
{
public:
    ...
    const int c {3};
    ...
};
Related