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!" }
user2084986
source share