Does the pointer actually call a virtual function?

Will a pointer to a member function of a class declared virtual be valid?

class A { public: virtual void function(int param){ ... }; } class B : public A { virtual void function(int param){ ... }; } //impl : B b; A* a = (A*)&b; typedef void (A::*FP)(int param); FP funcPtr = &A::function; (a->*(funcPtr))(1234); 

Will a B::function be called?

+6
c ++ function virtual function-pointers
source share
4 answers

Yes. It also works with virtual inheritance.

+2
source share

Yes. Valid code to check on codepad or ideone

 class A { public: virtual void function(int param){ printf("A:function\n"); }; }; class B : public A { public: virtual void function(int param){ printf("B:function\n"); }; }; typedef void (A::*FP)(int param); int main(void) { //impl : B b; A* a = (A*)&b; FP funcPtr = &A::function; (a->*(funcPtr))(1234); } 
+5
source share

A function is called because you are simply trying to call an inherited function.

0
source share

The best test for this purpose is to make methods in class A a pure virtual method. In both cases (with or without pure virtual methods), the B :: function is called.

0
source share

All Articles