I am using function pointer in my project, facing problem, created a test case to show it... below code fail with below error on MSVC2005 (in simple words i want to access dervied class function through base class function pointer)
error C2440: '=' : cannot convert from 'void (__thiscall ClassB::* )(void)' to 'ClassAFoo'
class ClassA {
public:
virtual void foo()
{
printf("Foo Parent");
}
};
typedef void (ClassA::*ClassAFoo)();
class ClassB : public ClassA {
public:
virtual void foo()
{
printf("Foo Derived");
}
};
int main() {
ClassAFoo fPtr;
fPtr = &ClassB::foo;
}
My questions are
- Is it C++ behavior that I cant access derived class function through a base class function pointer or its a compiler bug?
- I have been playing with above case, if i comment out
ClassB::foo
, this code compile fine, without any further modification, Why is this so, should notfPtr = &ClassB::foo;
again result in compile time error?
It's correct behaviour. Think of it this way: all instances of
ClassB
have the memberClassA::foo
, but not all instances ofClassA
have the memberClassB::foo
; only those instances ofClassA
which are actually the base class subobject of aClassB
instance have it. Therefore, assigningClassB::foo
intoClassAFoo
and then usingClassAFoo
in combination with a "pure"ClassA
object would try to call a nonexistent function.If you remove
foo
fromClassB
, the expressionClassB::foo
acutally refers toClassA::foo
which is inherited inClassB
, so there's no problem there.To elaborate on 1. further: pointers to members actually work the opposite way to normal pointers. With a normal pointer, you can assign
ClassB*
intoClassA*
(because all instances ofClassB
are also instances ofClassA
), but not vice versa. With member pointers, you can assignClassA::*
intoClassB::*
(becauseClassB
contains all the members ofClassA
), but not vice versa.Yes, it's ok. You cannot assign to function pointer of
class A
function pointer ofclass B
. You can do thisand overriden in
ClassB
function will be called.When there is no function
foo
inClassB
, function ofClassA
will be used. Live exampleFirst of all, I am not a C++ expert (I am trying to learn C++ so deep). So correct me if I am wrong and this an an experiment.
As part of learning about member function pointers, I was also searching for a code sample to call derived member using a base member function pointer. After going through this thread I created a code sample which is able to call derived member function even if member function is not a virtual.
I am using a Delegator to act as a Invoker. I hope it might helpful for some one. (Correct me If I am doing anything wrong)
output:
delegate.Invoke() will call Derived::SimpleMethod() and the output will be "Derived::SimpleMethod"**