6

Here's simple class definitions like

class Base{
    public:
        virtual void Func(){
            cout<<"Func in Base"<<endl;
        }
 };

 class Derived : public Base{
     public:
         virtual void Func(){
             cout<<"Func in Derived"<<endl;
         }
 }

 Base *b = new Derived();

and the statement

 (b->*&Base::Func)();

calls the Derived version of Func, different from b->Base::Func() which calls the base version as expected, why this happened and what's the meaning of that call exactly?

masoud
  • 55,379
  • 16
  • 141
  • 208
Qutard
  • 355
  • 2
  • 6
  • possible duplicate of [Pointers to virtual member functions. How does it work?](http://stackoverflow.com/questions/1087600/pointers-to-virtual-member-functions-how-does-it-work) –  Nov 18 '13 at 17:16

2 Answers2

5

The meaning of the call is to add verbosity. Basically: the expression &Base::Func is a pointer to member function, and (b->*x)() is the syntax for calling the member function pointed to by x on the object pointed to by b. In this case, since x is a constant, it's about the same as writing *&variable. It means the same as b->Func().

As to why it behaves differently from b->Base::Func, it's because the Base::Func are operands to the & operator, where the Base:: has a somewhat different role. If you'd written:

void (Base::*pmf)() = &Base::Func;

and called

(b->*pmf)();

you'd expect the virtual function to be called correctly. All the expression you've posted does is replace the variable pmf with a constant.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
3
&Base::Func

Means "take the address of the function Func in Base".

As it is a virtual function, it is not a simple function pointer, but actually stores the index into the virtual function table.

By then calling this with ->*, which means "derefence and access this member", you get the function at that index in b's virtual table, which is the Derived version. So it is basically the same as b->Func().

Why would someone do this? I have no idea!

I have explained a little about member function pointers previously, here (with pictures!).

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76