Monday, 25 May 2009

C++ Trivia :

Some trivia for you ( while I wait for a compile of 22 projects to take place… ) why does the code below not compile ?


The Problem


class AnotherClass
{};
class SomeClass
{
public:
SomeClass( AnotherClass anotherClass ){};
SomeClass( int someint ){};
void TheMethod(){};
};
int main(int argc, char* argv[] )
{
AnotherClass anotherClass;
SomeClass willCompile( anotherClass );
willCompile.TheMethod();

SomeClass wontCompile( AnotherClass() );
wontCompile.TheMethod();//error C2228: left of '.TheMethod' must have class/struct/union

return;
}


Confused.. good then I am not the only one…Lets take a quick detour to something that appears to be totally unrelated.


Quick Detour


Now given that one of the design decision of C++ was that it would be a superset of C, it has to allow for you the ability to define function pointers. So for a simple method you can define a prototype like this in your code for a method that takes 1 param ( typically you would do this as part of a typedef )


int Function(int a); 

As a short cut you can define your prototype without any param names ( since they are meaningless at this level ). 
int Function(int); 



In the same way you can also define the prototype for a method that takes a function pointer as a param


void TakesMethod( void Function( int  a ) );



Taking advantage of the “shortcut” you can equally write 


void TakesMethod2( void ( int ) );


The issue


Right so after a quick C/C++ lesson.. can you see the issue… ? Let make it a bit more obvious.. lets define a method that take a function pointer to a method that takes 0 params


void      TakesMethodNoParams(  void          () );
SomeClass wontCompile ( AnotherClass () );


Yup we just confused the compiler… it thinks we are defining a prototype for a method takes a function pointer as its single param, which is a method that takes no params, and returns a type of Anotherclass