Jump to content
  • Advertisement
Sign in to follow this  
dangerdaveCS

Calling derived function from base function

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

OK, I just want to check I've got this right so I can start looking elsewhere for my problem, if I have the following scenario:
class Base
{
	void Init()		{ Create();		}
	virtual void Create()	{ should not run;	}
}
class Derived : public Base
{
	void Create()		{ should run;		}
}

Derived* object = new Derived();
object->Init();


For some reason I keep getting the "should not run" result. Is my design pattern here OK? Is there something special I need to do to force a base classes function to call the derived version instead of its own? Cheers,

Share this post


Link to post
Share on other sites
Advertisement
Is Init actually the constructor? Because inside the constructor, virtual functions do not behave as you might expect. There is no dynamic dispatch, because the derived part of the object does not exist yet.

Share this post


Link to post
Share on other sites
The method init is declared only in the class Base. Class Base only knows its declaration of Create, so it cannot call the overloaded method of the Derived Class.

Share this post


Link to post
Share on other sites
Quote:
Original post by Matt77
The method init is declared only in the class Base. Class Base only knows its declaration of Create, so it cannot call the overloaded method of the Derived Class.


Not true. After the object has been constructed the vtables have been fixed up to point to the correct virtual functions, so calling "Create" from "Init" would behave exactly as expected.

dangerdaveCS: You code looks fine (ignoring syntax errors and not making things public). It looks like you quickly wrote up something to illustrate a problem you have in your real code somewhere. There is most likely an error in your actual code preventing inheritance from functioning properly. Did you perhaps forget to put "virtual" in front of Base::Create?

If you're still having issues you should probably post the actual code you're looking at, then we may be of greater assistance.

Share this post


Link to post
Share on other sites
sorry, i missed the virtual keyword in the Base method.
That being said, your example should work as you expected.

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!