I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
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 function fun()
is non virtual , it will be resolved at complie time (i.e, for this line it will jump to instruction X at code section with this
pointer as NULL
).
As no member variable and no virtual function are used/called in fun()
function, it is working fine.
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).
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
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.
I have tried multiple times,all the time output is coming "fun" this is because function fun
is independent of instance a
. while calling a->fun();
a
points to 0 so this is undefined behavior but in most of the compilers there should be no crash.
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?.
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 call fun()
fun()
never access any member variables in A
so it doesn't need to dereference
the null this
pointer.