user103214
user103214

Reputation: 3658

Pointer to a member of class

In my class, If I want to point to a member of class,

struct S
{
     static int get();
     int do_something();
     int x;
};

I do,

int (*p)() = S::get;

Unfortunately this doesn't for non-static member

int (*p)() = S::do_something; // error

Since, a static member function is an ordinary function, and from the quote I came around below states that a non-static member function is also a ordinary function so why wouldn't it work? what does it mean?

(9.2/10) [Note: the type of a nonstatic member function is an ordinary function type, and the type of a nonstatic data member is an ordinary object type. There are no special member function types or data member types. ]

Upvotes: 2

Views: 174

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477620

Non-static member functions are not ordinary functions. You cannot form free pointers to them.

The only permissible way to refer to a non-static member function is through a pair of an instance pointer/reference and a pointer-to-member-function:

S * p = &theobject;
int (S::*ptmf)() = &S::do_something;

return (p->*ptmf)();

Unlike member objects (to which you can very well form a free pointer, e.g. &theobject.x), member functions are more complicated, because you need to account for virtual functions: If S is a polymorphic base class and p is a pointer-to-base and do_something() is virtual, then the above example should perform the correct type of dispatch. A simple free function pointer cannot do this.

(Moreover, the standard does not specify how each underlying implementation of member functions is implemented, so this detail is never exposed to the user. Typically it'll be something like int S_mangled_name_do_something(S *);, but that's not specified.)

Here are some related answers of mine on the subject: #1, #2.

Upvotes: 5

BruceAdi
BruceAdi

Reputation: 1989

int (S::*p)() = S::do_something;

a non-static member function is an ordinary function except that there is an invisible parameter this.

Upvotes: 0

Björn Pollex
Björn Pollex

Reputation: 76876

The type of the function is ordinary, not the type of the function-pointer. A pointer to a non-static member-function has to be declared like this:

typedef int (S::*p)() ptr_to_member_of_s;

Upvotes: 2

Related Questions