Whenever I define a variable and give it a value at the same time inside a class, I get an error. What is the reason for this?
As you can see, this doesn’t work…
class myClass {
private:
int x = 4; // error
};
But when I keep the variable undefined it does:
class myClass {
private:
int x;
};
Since no one else is using member initialization, I’ll introduce you:
It’s always better to use this over assigning in the body of the constructor, since by the time the body begins, all user-defined members will have already been initialized whether you said so or not. Better to do it once and actually initialize the non-user-defined members, and it is the only method that works for both non-static
constmembers, and reference members.For example, the following will not work because
xisn’t being initialized in the body, it’s being assigned to:Using a member initializer, however, will, because you’re initializing it off the bat:
Note also that your
int x = 4;syntax is perfectly valid in C++11, where it subs in for any needed initialization, so you’ll benefit if you start using it.