class foo
{
int a, b;
public:
foo() : a(3), b(a+1) {}
};
C++ construction and initializing member variables
Hi:
Does the C++ standard specify in what order variables are inititialized in a constructor? Are they like parameters, where there's no guarantee the order they're initialized?
For example, say I've got a class like this:
Will a be set to 3, and then b be 4, or is it like passing parameters to a function, and you don't know what b will be set to?
TIA
BC
Member variables are initialized in the order in which they are declared in the class definition, regardless of the order in which they are listed in the constructor initializer list. Base class members will be initialized before any members of the current class.
In your case, a will always be initialized before b, regardless of whether you write foo() : a(3), b(a+1) {} or foo() : b(a+1), a(3) {}. In fact, a good compiler will issue a warning for the latter.
In your case, a will always be initialized before b, regardless of whether you write foo() : a(3), b(a+1) {} or foo() : b(a+1), a(3) {}. In fact, a good compiler will issue a warning for the latter.
http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=169&rl=1
base classes first, then the members of the class from top to bottom
base classes first, then the members of the class from top to bottom
If that is true, why does GCC spam warnings if your initializer list is in a seperate order than the variables are declared in the header?
I swear I've read somewhere that the order of the variables in the initializer list does matter, though I think it really only affects situations where you are initializing one variable with the value of another in the initializer list in the wrong order. This if probably the reason for the warnings right?
Thx
edit: nm the end of Frunys post answered my question. missed that before I posted
I swear I've read somewhere that the order of the variables in the initializer list does matter, though I think it really only affects situations where you are initializing one variable with the value of another in the initializer list in the wrong order. This if probably the reason for the warnings right?
Thx
edit: nm the end of Frunys post answered my question. missed that before I posted
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement