Jump to content
  • Advertisement
Sign in to follow this  
cnstrnd

Initializers list order (base class VS members)

This topic is 5052 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

Look,
#include <iostream>

class Needed
{
public:

	Needed( int i )
		: i( i )
	{}

	int i;
};

class Base
{
public:

	Base( Needed& needed )
	{
		std::cout << needed.i;
	}
};

class Derived : public Base
{
public:

	Derived()
		: needed( 123 )
		, Base( needed )
	{}

	Needed needed;
};

int main( int argc, char* argv [] )
{
	Derived derived;
}
I declare a instance of class "Needed" in "Derived" because "Base" constructor uses it as an argument. This compile fine but it prints uninitialized garbage instead of "123". Is it possible to construct the "Needed" instance in "Derived" before constructing the "Base" class ?

Share this post


Link to post
Share on other sites
Advertisement
Only if you make the Needed object static, the standard requires the base class to be constructed before the Needed member object otherwise.

Share this post


Link to post
Share on other sites
It really doesn't make much sense; objects are constructed starting from the root of the inheritance hierarchy to the leaf—in a sense, there is a point where your Derived object is a Base object, before it is decorated with its final type.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!