Jump to content
  • Advertisement
Sign in to follow this  
nlbs

Initializing parent Class's member variables from base's --- Base's Constructor

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

say for an example C extends B extends A e.g. A is Grand, P is Parent, and C is Child and A have a member variable called __data which is protected. so would it be possible to initialize A's __data from C through C's Constructor like C::C():__data(0) My Compiler (g++) fires error saying Class C doesnt have a field named __data

Share this post


Link to post
Share on other sites
Advertisement
Nope. One way is to have a protected 1 argument constructor at every level of the inheritance chain:

class A
{
protected:
A(int data)
:
data(data)
{
}

int data;
};

class B : public A
{
protected:
B(int data)
:
A(data)
{
}

};

class C : public B
{
public:
C()
:
B(42)
{
}
};



Also note that the symbol __data is reserved for the compiler, as are all symbols that being with two underscores or an underscore and a capital letter.

Share this post


Link to post
Share on other sites
Sorry, __data is already constructed before C::C() ever gets to touch it.

There are two solutions:

1) Give A a constructor that will initialise __data with a passed value. Then give B a constructor that will pass a value through to A's constructor. Then have C's constructor pass the initialising value to B's constructor.

2) Use assignment to set the value of __data in C::C(), I.e.

C::C() { __data = 0; }


By the by, leading underscores are reserved for the implementation, don't use them in your own code.

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!