It might be obvious for who knows the background magic, but I could not understand how below code is giving correct output. I expected a runtime error. Please help.
a::print
is a not a virtual method, hence it is just a normal function that has an extra argument to receive the this
pointer. Since the method never uses the this
pointer, the fact that it is uninitialized doesn't turn into a memory access error or other failure. Declaring a::print
static
will still compile in this case since it doesn't use the this
pointer. Declaring a::print
virtual
or accessing this
inside the method will likely lead to the program crashing, at least under some circumstances.
The behavior is still undefined and it is an ill-formed program, but as it stands now it is very likely to work deterministically on most systems. In general C++ does not give runtime errors for such cases, but if you compile with e.g. "clang++ -Wall" a warning indicating the uninitialized variable will be given. (And there are tools such as clang's asan which will go further in diagnosing such errors.)