First of all, using C-style typecasts on C++ types is a very bad idea. Use
dynamic_cast
,
static_cast
, etc. instead (and make sure you know exactly when to use which: see
http://www.cplusplus.com/doc/tutorial/typecasting/[
^] )
Second, without virtual functions, inheritance doesn't make sense. But I'll assume for now this is just an oversimplifaction on your part to focus on the code in question. [edit]does not relate to the question - please ignore[/edit]
Third, C style typecasts will always be accepted by the compiler: they basically tell the compiler that you know better than the compiler does. (IME this is very often a misconception, and in this case it definitely is)
Last, this works because you were lucky: What happens here is that on the stack, an object of type
Derived1
is created, with the appropriate size to fit such an object. Then, you the compiler that in truth this is an object of type
Derived2
instead. Because you used C-style typecasting the system will comply to your wish without question and overlay the memory layout of
Derived2
over the memory occupied by
obj2
. This will work for as long as you don't try to use virtual functions, or data members, but when you call
Fun1()
, you actually write into a data member: Since the memory orginally allocated is not big enough to fit
Derived2
, you're writing outside the bounds of that memory.
Normally, this causes other variables to be corrupted, but it seems that you were lucky in this case. I believe that internally, the stack variables are stored in reverse order of declaration: in this case
pBase
first, then
obj2
. If it had been the other way round, you would have overwritten
pBase1
and the last line of your code would likely have crashed,