Jul 2, 2008

What is wrong with this code?

I was reading some blogs this week and find an interesting story related to references in C++ (and as it has some time that I don't work/post about C++) so I decided to post about it. Take a look in the code and try to answer the following questions below:
#include "stdafx.h"
#include "stdio.h"

class SimpleClass
{
public:
SimpleClass(int n)
{
   value = n;
}

void FirstMethod(TCHAR* str)
{
  wprintf(str);
}

void SecondMethod()
{
  wprintf(L"Value: %d", value);
}

private:
int value;
};

void Test(SimpleClass &ref, int i)
{
switch(i)
{
  case 1:
     ref.FirstMethod(L"Hello world\r\n");
     break;

  case 2:
     ref.SecondMethod();
     break;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
SimpleClass *p = 0;

Test(*p, 1);
Test(*p, 2);

return 0;
}
  • Will it compile? run?
  • What would be the outcome from Test being called in line 39?
  • What about line 40?
  • Is there any other issues?
(PS: VS 2008 compiled it with no warnings....) Adriano

1 comment:

Anonymous said...

Of course it compiles since it has no way of knowing that the pointer is referencing NULL.

The first test passes because the function table is non virtual and does not reference any member variables.

The second fails because it actually goes to the reference to retrieve value.

If you change FirstMethod to be virtual it will crash there because the runtime needs a to use the virtual function pointer.