Jump to content
  • Advertisement
Sign in to follow this  
Couvillion

C++ construction and initializing member variables

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!