What is the value of (base & # 8594; * & Func) () in C ++

Here are simple class definitions such as

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 statement

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

calls a derivative version of Func, other than b-> Base :: Func (), which calls the base version, as expected, why did this happen and what is the point of this call?

+6
source share
2 answers

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

As for why it behaves differently from b->Base::Func , it is because Base::Func are operands of the & operator, where Base:: has a slightly different role. If you wrote:

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

and called

 (b->*pmf)(); 

You expect the virtual function to be called correctly. The entire expression you sent replaces the pmf variable with a constant.

+5
source
 &Base::Func 

The tool "accepts the address of the Func function in Base ".

Since this is a virtual function, it is not a simple pointer to the function, but actually stores the index in the virtual function table.

Then, calling this with ->* , which means β€œremoving and accessing this element”, you get a function in that index in virtual table b , which is a version of Derived . So it is basically the same as b->Func() .

Why would anyone do this? I have no idea!

I explained a bit about member function pointers earlier, here (with pictures!) .

+3
source

Source: https://habr.com/ru/post/958325/


All Articles