I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
What will happen when this code is executed, and why?
I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
What will happen when this code is executed, and why?
We can't know what will. Everything can happen, because the program exposes undefined behavior. See Does invoking a member function on a null instance cause undefined behavior?.
It won't compile.
Class
keyword, which should be lowercase.fun()
is private.fun()
is not virtual, so there's no need to refer to a vtable to call fun()
fun()
never access any member variables in A
so it doesn't need to dereference
the null this
pointer.It's undefined behavior, so anything might happen.
A possible result would be that it just prints "fun"
since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).
Others have pointed out many issues - let me just throw in my association for "tricky": (supposed you change Class
to class
) it depends on how NULL
is defined ;-)
Evil example:
A anotherA();
#define NULL &anotherA;
...
OK, as I realize it wouldn't work this way directly, since you must put these two lines between the definition of class A
and that of a
... but I am fairly sure there is an evil enough way to actually make this technically possible :-(
Was this a question about your knowledge of C++ or a question about code reading skills and/or debugging skills? Other than the fact that a C++ class is being used, this kind of problem is language-agnostic.
By the standard, this is undefined behavior and therefore a very bad thing. In reality of most programming platforms (across both X86 and several other architectures) this will run fine.
Why? Consider how class functions are implemented in C++. This isn't a virtual function, therefor this can be a static call to a known address. In assembly, we can see this as mov A, 0 mov ecx, A call a__fun
since a__fun requires no instance data, even though it receives a null this pointer, nothing will happen.
Still shitty code and any compiler will scream, but it can run.