I suspect this not a good thing to do having read the documentation of reinterpret_cast.
You need to remember that a simple class like this with no data members is just a list of function pointers that are the same for all instances of the class. Since there are no member variables for DervEx::Print to access the code works.
If you change DervEx to
- class DervEx : public BaseEx
-
{
-
public :
-
int i;
-
-
DervEx(void) : i(5) {}
-
void Display()
-
{
-
cout<<"Derv:: Display()"<<endl;
-
}
-
-
void Print()
-
{
-
cout<<"Derv:: Print(): "<<i<<endl;
-
}
-
};
You will see that the output is garbage because the data actually pointed at is garbage and not an actual DervEx class.
You would only get a crash if you attempted to access a piece of memory outside the legal bounds for your platform, in MSVC (what I am using) since the heap starts at several k and all the used data is on the heap and very small the extra location accessed by DervEx::i is still valid even though it is not an actual part of the class.
The documentation that I have of reinterpret_cast states that you should not use pointers cast in this way as you have no garantee about there validity in fact you code works if you change
DervEx *d = reinterpret_cast<DervEx *> ( new BaseEx);
to
DervEx *d = reinterpret_cast<DervEx *> (new int);
I think the point is that you should only use reinterpret_cast in very special circumstances not in normal use and having used it if you have converted pointer types you should not be using the new pointer.