Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the meaning of (base->*&Func)() in C++

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?

like image 230
Qutard Avatar asked Nov 18 '13 17:11

Qutard


2 Answers

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.

like image 111
James Kanze Avatar answered Oct 17 '22 02:10

James Kanze


&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!).

like image 23
BoBTFish Avatar answered Oct 17 '22 02:10

BoBTFish