Function pointers and overridden functions in C ++

I'm new to C ++, and now I'm confused about the concept of polymorphism and function pointers. It got a little mixed up in my head.

In the code below, I declare a pointer to a function that points to a method in BaseClass. Then I assigned it using & BaseCass :: Print

The last two lines are the part that I confused: why these two lines do not give the same result? I guess, because the myPtr pointer points to a v-table, but I'm not sure. Also, if I want myPtr to call the overridden function BaseClass :: Print (), how can I do this?

Can someone clarify this to me? Thanks.

#include <iostream> using namespace std; class BaseClass{ public: virtual void Print(){ cout << "Hey!" << endl; } }; class DerivedClass : public BaseClass { public: void Print(){ cout << "Derived!" << endl; } }; int main() { BaseClass *b = new DerivedClass; void (BaseClass::*myPtr)(); myPtr = &BaseClass::Print; (b->*myPtr)(); //print "Derived!" b->BaseClass::Print(); //print "Hey!" } 
+4
source share
2 answers

String (b->*myPtr)(); invokes the BaseClass::Print b element. BaseClass::Print is a virtual function, and since you call it through a pointer type, it will look polymorphic. That is, the correct function will be found in accordance with the dynamic type b (which is equal to DerivedClass ).

Second line b->BaseClass::Print(); explicitly calls the Print member function, which is a BaseClass member. This is exactly what this syntax is for. It says: "Hey, I don't care what dynamic type b is - I want you to name the BaseClass version.

+4
source

Even if you created an object of type DerivedClass , it still has information about the class from which it inherits, in this case, BaseClass . Therefore, when you use:

b->BaseClass::Print();

You just ask to call the Print() parent - BaseClass method from it.

+1
source

All Articles