Calling derived function from base function

Started by
4 comments, last by Matt77 14 years ago
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,
Dave.
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.
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.
Post your actual code; because the code posted (with slight variations) works perfectly.

Here

[size=1]Visit my website, rawrrawr.com

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.

This topic is closed to new replies.

Advertisement