Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a pointer to a virtual function still get invoked virtually?

Will a function pointer to a class member function which is 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 B::function be called?

like image 390
uray Avatar asked Nov 19 '10 18:11

uray


People also ask

Can we use this pointer with virtual function?

Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.

Which is not true about virtual function in C++?

​Hence, Virtual functions cannot be static in C++.

Do virtual functions have to be overridden?

¶ Δ A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax.

Which is true about virtual function?

Which among the following is true for virtual functions? Explanation: The prototype must be the same. Because the function is to be overridden in the derived class.


2 Answers

Yes. Valid code to test 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);
}
like image 148
Matthieu Avatar answered Oct 06 '22 16:10

Matthieu


Yes. It also works with virtual inheritance.

like image 34
Alexandre C. Avatar answered Oct 06 '22 17:10

Alexandre C.