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?
Virtual functions should be accessed using pointer or reference of base class type to achieve runtime polymorphism.
Hence, Virtual functions cannot be static in C++.
¶ Δ 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 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.
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);
}
Yes. It also works with virtual inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With