Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification on pointer to non-static class member

When I need a pointer to member of class, I do as following

struct MyStruct
{
    int foo();
};

int (MyStruct::*p)() = &MyStruct::foo;

My question is why do I need to use & operator to take the address which may be ignored if it were a static function. Also, I've heard pointer to members aren't really a pointer, Can someone clarify that?

like image 745
user1086635 Avatar asked Mar 03 '26 02:03

user1086635


1 Answers

If it's a static function, it works just as a regular non-member function pointer: the function name itself can be implicitly converted to a function pointer.

If it's a non-static member function, it's no longer the same thing as a non-member function:

  1. It has a hidden this parameter;
  2. In a multiple inheritance scenario, converting a pointer to one of the base classes may produce a pointer to a different address. This means that if the member function is inherited, the this pointer may need to be adjusted before the call. This already makes it impossible to use a pointer to store a pointer-to-member-function.

Raymond Chen wrote an interesting article about this with more details and examples.

like image 78
R. Martinho Fernandes Avatar answered Mar 05 '26 15:03

R. Martinho Fernandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!