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();
Calling derived function from base function
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:
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,
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.
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.
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.
sorry, i missed the virtual keyword in the Base method.
That being said, your example should work as you expected.
That being said, your example should work as you expected.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement