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,