When using multiple inheritance C++ has to maintain several vtables which leads to having "several views" of common base classes.
Here s a code snippet:
#include "stdafx.h"
#include <Windows.h>
void dumpPointer( void* pointer )
{
__int64 thisPointer = reinterpret_cast<__int64>( pointer );
char buffer[100];
_i64toa( thisPointer, buffer, 10 );
OutputDebugStringA( buffer );
OutputDebugStringA( "
" );
}
class ICommonBase {
public:
virtual void Common() = 0 {}
};
class IDerived1 : public ICommonBase {
};
class IDerived2 : public ICommonBase {
};
class CClass : public IDerived1, public IDerived2 {
public:
virtual void Common() {
dumpPointer( this );
}
int stuff;
};
int _tmain(int argc, _TCHAR* argv[])
{
CClass* object = new CClass();
object->Common();
ICommonBase* casted1 = static_cast<ICommonBase*>( static_cast<IDerived1*>( object ) );
casted1->Common();
dumpPointer( casted1 );
ICommonBase* casted2 = static_cast<ICommonBase*>( static_cast<IDerived2*>( object ) );
casted2->Common();
dumpPointer( casted2 );
return 0;
}
it produces the following output:
206968 //CClass::Common this
206968 //(ICommonBase)IDerived1::Common this
206968 //(ICommonBase)IDerived1* casted1
206968 //(ICommonBase)IDerived2::Common this
206972 //(ICommonBase)IDerived2* casted2
here casted1
and casted2
have different values which is reasonable since they point to different subobjects. At the point when the virtual function is called the cast to the base class has been done and the compiler doesn t know that it was a most derived class originally. Still this is the same each time. How does it happen?