And why not? Standard say that this program has undefined behavior, but in C++ we have 3 kind of functions in a class:
// 1) static functions
class test {
public:
static void foo( int n );
};
In this example foo
is like a global function with same signature, but C++ have a different rule for access check and name of it.
// 2) normal member functions
class test {
public:
void foo( int n );
};
In almost all compilers this function is same as a a free function with signature void foo(foo* this, int n)
and this is not an error to call this function with an invalid this
unless you access this
in the function that in that case function possibly generate segmentation fault or even worse, change some unexpected point of your memory.
// 3) virtual functions
class test {
public:
virtual void foo( int n );
};
In this case class test
contain an extra invisible member that usually called vtable
and contain one pointer to implementation of each virtual
function of the class and using this technique C++ can have late binding at runtime, so in this case when you call foo
compiler write something like
this->vtable[foo_index]( this, n );
so in this case invalid this
immediately show itself and possibly generate errors like segmentation fault or invalid instruction, since you access this
at point of call. So as you see in almost all implementation you can have a member function that called through an invalid this
pointer and never generate any error(if you never access this
in the function), but it can't be virtual
.
But remember what explained above completely depend on your compiler, but almost all compilers implement it like above.