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?
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.
&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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With