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?
Adriano

1 comments:
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.
Post a Comment