Sign in to follow this  

Initializers list order (base class VS members)

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

This topic is 4836 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this