Error with member function address in parentheses

I found something interesting. The error message says it all. What is the reason that the address of the non-static member function is not indicated in parentheses? I compiled it on gcc 4.3.4.

#include <iostream> class myfoo{ public: int foo(int number){ return (number*10); } }; int main (int argc, char * const argv[]) { int (myfoo::*fPtr)(int) = NULL; fPtr = &(myfoo::foo); // main.cpp:14 return 0; } 

Error: main.cpp: 14: error: ISO C ++ prohibits accepting the address of an unqualified or non-stationary non-stationary member function to form a pointer to a member function. Say '& myfoo :: foo'

+32
c ++ function-pointers pointer-to-member
Aug 20 '11 at 19:39
source share
2 answers

From the error message, it looks like you are not allowed to accept the address of the expression in parentheses. It means you are rewriting

 fPtr = &(myfoo::foo); // main.cpp:14 

to

 fPtr = &myfoo::foo; 

This is due to the specification part (& sect; 5.3.1 / 3) that reads

A pointer to a member is formed only when explicit and used, and its operand is an identifier not enclosed in parentheses <...>

(my emphasis). I'm not sure why this is the rule (and I still didn't know about it until now), but it seems like the compiler is complaining.

Hope this helps!

+24
Aug 20 '11 at 19:44
source share

Imagine this code:

 struct B { int data; }; struct C { int data; }; struct A : B, C { void f() { // error: converting "int B::*" to "int*" ? int *bData = &B::data; // OK: a normal pointer int *bData = &(B::data); } }; 

Without a trick with parentheses, you cannot take a pointer directly to data element B (you will need base class throws and playing with this is not nice).




From ARM:

Note that the operator address must be used explicitly to get a pointer to an element; there is no implicit conversion ... If it were, we would have ambiguity in the context of the member function ... For example,

 void B::f() { int B::* p = &B::i; // OK p = B::i; // error: B::i is an int p = &i; // error: '&i'means '&this->i' which is an 'int*' int *q = &i; // OK q = B::i; // error: 'B::i is an int q = &B::i; // error: '&B::i' is an 'int B::*' } 

IS just kept this concept of pre-Standard and explicitly mentioned that parentheses do this so that you don't get a member pointer.

+14
Aug 21 2018-11-21T00:
source share



All Articles