Sign in to follow this  
dangerdaveCS

Calling derived function from base function

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

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