home bbs files messages ]

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,818 of 33,346   
   Thomas Richter to All   
   Re: C'tor vs. function declaration   
   19 Jan 12 14:56:02   
   
   f1105031   
   From: thor@math.tu-berlin.de   
      
   Am 18.01.2012 21:12, schrieb Michael Smolensky:   
   > Consider an example:   
   >   
   > struct S   
   > {   
   >   S( int ) {}   
   > };   
   >   
   > class C   
   > {   
   > public:   
   >   C() {}   
   >   C( int ) {}   
   >   C( S ) {}   
   >   
   >   int get_int() { return 0; }   
   > };   
   >   
   > int main()   
   > {   
   >   C obj0;   
   >   
   >   int i = 0;   
   >   
   >   C obj1( S( obj0.get_int() ) );  // (1) c'tor C( int )   
   >   C obj2( S( i ) );               // (2) function decl C ()( S )   
   >   C obj3( (S( i )) );             // (3) c'tor C( int )   
   >   C obj4( *&S( i ) );             // (4) c'tor C( int )   
   >   
   >   obj0 = obj1;                    // (5) OK   
   >   obj0 = obj2;                    // (6) error: cannot convert   
   > function ptr to int   
   >   obj0 = obj3;                    // (7) OK   
   >   obj0 = obj4;                    // (8) OK   
   >   
   >   return 0;   
   > }   
   >   
   > Both GCC 4.1 and VC9 treat line (2) as a function declaration, not a   
   > constructor C( S ). Workarounds like (3) and (4) work as expected. Can   
   > someone explain?   
      
   This is C++'s "most vexing parse". The standard requires this behavior: If it   
   looks like a function declaration, it must be parsed as a function declaration   
   and not as a constructor call. The problem with the syntax   
      
   C obj(S(i))   
      
   is that as soon as the compiler parses off the "S", it is identified as a   
   function declaration - when the next bracket is seen, it is too late already.   
      
      
      
   --   
         [ 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