Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is initializing non static members allowed outside of a class constructor?

I just saw a question where a non static member of a class was initialized in the class definition. But if I try to compile the following code I get an error from the compiler.

class MyClass
{
    int n = 2;
};

The error I'm getting is:

g++ -o ns nonstatic.cpp -Wall -Wextra -pedantic
nonstatic.cpp:3:13: error: ISO C++ forbids initialization of member ‘n’ [-fpermissive]
nonstatic.cpp:3:13: error: making ‘n’ static [-fpermissive]
nonstatic.cpp:3:13: error: ISO C++ forbids in-class initialization of non-const static member ‘n’

I always thought I must initialize such member in the constructor like this:

class MyClass
{
    public:
        MyClass ( void ) : n(2) {}
    private:
        int n;
};

Or with n initialized inside of the body of the constructor. So my question is: when is one allowed to initialize a non static member outside the context of a class constructor?

kind regards,

like image 556
hetepeperfan Avatar asked Feb 16 '23 02:02

hetepeperfan


1 Answers

when is one allowed to initialize a non static member of a class in C++?

One can do this already in C++11.

Just pass in -std=c++11 to the command line and you'll be able to.

like image 164
Rapptz Avatar answered May 01 '23 22:05

Rapptz