Reputation: 8802
How can I initialize a member variable of a POD (Plain Old Data) in C++11?
class A {
public:
int theAnswer; // this is not initialized
};
static_assert(std::is_pod<A>::value, "A must be a plain old object");
class B {
public:
int theAnswer { 42 }; // this should initialize to 42
};
static_assert(std::is_pod<B>::value, "B must be a plain old object"); // ERROR
class C {
public:
C() : theAnswer { 42 } { } // Obviously, this is not a trivial default constructor, so it does not work
int theAnswer;
};
static_assert(std::is_pod<C>::value, "C must be a plain old object"); // ERROR
Upvotes: 5
Views: 549
Reputation: 41301
Here is some standardese explaining why you can't initialize POD members inside the class itself.
[class]/10
:
A POD struct is a non-union class that is both a trivial class and a standard-layout class
[class]/6
:
A trivial class is a class that has a default constructor (12.1), has no non-trivial default constructors, and is trivially copyable.
[class.ctor]/4
:
A default constructor is trivial if it is not user-provided and if:
— its class has no virtual functions (10.3) and no virtual base classes (10.1), and
— no non-static data member of its class has a brace-or-equal-initializer, and
— all the direct base classes of its class have trivial default constructors, and
— for all the non-static data members of its class that are of class type (or array thereof), each such class has a trivial default constructor.
Upvotes: 2
Reputation: 71989
You do it where you initialize the whole object. A plain old data object is just that: plain old data, with no invariants, initialization, or any of that fancy stuff. If you want initialization, then it's not POD.
But maybe you don't actually need a POD. Maybe trivially copyable is enough? If all you want to do is memcpy between objects, trivially copyable is the trait you're looking for, not POD.
Upvotes: 10