Function pointers and overridden functions in C++
c++
Solution
The line `(b->*myPtr)();` calls the `BaseClass::Print` member of `b`. `BaseClass::Print` is a virtual function and, since you're calling it through a pointer type, will be looked up polymorphically. That is, the correct function according to the dynamic type of `b` (which is `DerivedClass`) will be found.
The second line `b->BaseClass::Print();` explicitly calls the `Print` member function that is a member of `BaseClass`. That's precisely what this syntax is for. It says "Hey, I don't care what the dynamic type of `b` is - I want you to call the `BaseClass` version."
Problem
I'm new to C++, and I'm now confused about the polymorphism concept and function pointers. It's kinda mixed up in my head. In the code snipped below, I declare a function pointer that points to a method in BaseClass. Then I assigned it with &BaseClass::Print The last two lines is the part i get confused: why these two lines doesn't yield the same result? I guess it's because the pointer myPtr points to the v-table, but i'm not sure. Also, if I want to make myPtr call the overridden BaseClass::Print() function, how could I do so? Could anyone please 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!" } ```