Forums before death by AOL, social media and spammers... "We can't have nice things"
|    comp.lang.c++.moderated    |    Moderated discussion of C++ superhackery    |    33,346 messages    |
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
|    Message 31,482 of 33,346    |
|    =?ISO-8859-1?Q?Daniel_Kr=FCgler?= to Agents Marlow    |
|    Re: help needed with pointer to member f    |
|    23 Sep 11 12:03:20    |
   
   dc4f7226   
   From: daniel.kruegler@googlemail.com   
      
   On 2011-09-23 15:08, Agents Marlow wrote:   
   > Hello,   
   >   
   > I took a brainbench test recently in which there was the following   
   > code:   
   >   
   > struct X {   
   > int foo() { return 0; }   
   > } x;   
   >   
   > struct Y {   
   > static int (X::*p)();   
   > };   
   >   
   > int (X::*Y::p)() = X::foo;   
   >   
   > int main()   
   > {   
   > // insert answer here   
   > return 0;   
   > }   
   >   
   > The question was about what to put at // insert answer here to invoke   
   > function foo.   
   >   
   > I didn't know, guessed and got it wrong. So out of curiosity I tried   
   > the code above with g++ but got a compilation error in the assignment   
   > statement. The error report said:   
   >   
   > a3.cpp:9: error: invalid use of non-static member function 'int   
   > X::foo()'   
   >   
   > Can anyone tell me what is wrong please?   
      
   The code is ill-formed. To retrieve the pointer of a member you also   
   need the & operator as in:   
      
   int (X::*Y::p)() = &X::foo;   
      
   See 5.3.1 p4:   
      
   "A pointer to member is only formed when an explicit & is used and its   
   operand is a qualified-id not enclosed in parentheses."   
      
   > I thought the line was trying to assign a value to the class-wide   
   > variable p in Y.   
      
   It does not *assign* a value, but it is used as *initializer* for it.   
      
   > The variable is a pointer to a member function.   
      
   Correct.   
      
   > The function has no args and returns an int. The member function assigned   
   > is X::foo. The X::foo member function is not static. The variable Y::p   
   > is static but IMO this should not matter at all.   
      
   Of course it matters, because if it were not a static member you would   
   need here an object of type Y, where the data member would belong to.   
      
   > When invoking Y::p   
   > there will have to be an object so presumably object x will be used.   
      
   Yes.   
      
   HTH & Greetings from Bremen,   
      
   Daniel Krügler   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|
[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]
(c) 1994, bbs@darkrealms.ca