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?.
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 x86 assembly, we can see this as
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.
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).The most likely behavior, on most modern computers, is that it will run, and print "fun", because:
fun()
is not virtual, so there's no need to refer to a vtable to callfun()
fun()
never access any member variables inA
so it doesn't need to dereference the nullthis
pointer.Three points might help:
1) All Functions are stored in code or text section.
2) Non Virtual functions are resolved at complie time.
3) While calling to member functions of class, we pass current object as
this
pointer to that function.Coming to your question , here
fun()
function is already in memory(code section / text section). As functionfun()
is non virtual , it will be resolved at complie time (i.e, for this line it will jump to instruction X at code section withthis
pointer asNULL
). As no member variable and no virtual function are used/called infun()
function, it is working fine.I have tried multiple times,all the time output is coming "fun" this is because function
fun
is independent of instancea
. while callinga->fun();
a
points to 0 so this is undefined behavior but in most of the compilers there should be no crash.