C++ construction and initializing member variables

This topic is 4819 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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:
class foo
{
int a, b;
public:
foo() : a(3), b(a+1) {}
};


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

Share on other sites
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.

Share on other sites
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

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 16
• 12
• 20
• 12
• 18
• Forum Statistics

• Total Topics
632160
• Total Posts
3004500

×