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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With