Well I can see why you would want it to fail, and
Func1
doesn't exist on
Base
how can it be Ok to call that method?
The thing is when you do the down-cast using
static_cast
you're essentially telling the compiler "
just trust me on this, I know what I am doing" and since the
Func1
method in you example doesn't touch any data related to the instance it's going to "work" even though it really shouldn't (this is because instance functions are pretty much just static functions where the compiler pass the instance as a secret first parameter called
this
).
To check this you can add an
int
member initialized to
0
to
Derived
and print it's value in
Func1
, when
Func1
is called for a
Derived
it will have a the value of the memory where the
int
would have been had it been a
Derived
instance.
What you want to do is not use
static_cast
and use
dynamic_cast
with
Runtime Type Information enabled, that might cause it to fail earlier.
Remember that C++ will let you do whatever you want, so you need to be careful, for example, you could add the following to your code;
string s = *reinterpret_cast<string*>(pB1);
And it would compile and run. Behaviour of that string will be undefined though.