class Base
{
virtual void Foo(){}
virtual void Bar(){}
};
class Derived1 : public Base
{
void Foo(){ //Do something }
void Bar(){ //Do something }
}
class Derived2 : public Base
{
void Foo(){ //Do something }
void Bar(){ //Do something }
}
class OtherClass
{
public:
Base* obj;
void (Base::*method)();
void Add( Base* _obj, void (Base::*_method)() )
{
obj = _obj;
method = _method;
}
void Run()
{
( obj->method )();
}
}
int main()
{
Derived1 d1;
Derived2 d2;
OtherClass other;
other.Add( &d1, &(Derived1::Foo) );
//other.Add( &d2, &(Derived2::Bar) ); etc, etc.
other.Run();
}
My question:
Say I have a derived class with a method, I can refer to an instance of that class with a pointer of it's base type. Assuming I know what method I want to call, I can then call it via that pointer and the derived class's method will be called.
How can I achieve similar polymorphic behaviour when I specify the method to be called by supplying a method pointer?
The real code the above is based on will compile if I cast the method pointer, but it appears to not be doing any-- It is at this point I've realised I wasn't calling OtherClass's update method, which is why I wasn't getting any joy. :D So this works, as is (almost). Stupid, stupid brain.
Slight course correction then: Right now I need to static cast the method pointer I pass to OtherClass, to a pointer to Base class method when I pass it to Add. This is not ideal.
Can I get the same behaviour if I pass &(Base::Foo), for example, to the method Add?
Will Derived1::Foo be called if I invoke that method on a pointer to base type that refers to an instance of the derived type?
I get the feeling it'll call the base member. :(
Some reading: Is it safe to "upcast" a method pointer and use it with base class pointer? C++ inheritance and member function pointers Pointer to member conversion Casting a pointer to a method of a derived class to a pointer to a method of a base class