Casting About
Notes
We need to examine casting a bit.
static_cast
Used when there are built in routines (int to float)
Or when classes provide constructors (RationalT(int real))
Or when changing pointers
Casting from a derived class to a more general (towards base) is called upcasting
BarbarianT barbarian; FighterT * fp = & barbarian;
This is not dangerous in that data is lost, but the base class does not expect for there to be data.
And virtual functions will still work because the vtable/ run time system.
Casting from a general class to a derived class is called downcasting
This is truly a problem
The specialized (derived) class potentially has more members than the base class.
But these are not present in the base class that was cast to it.
So there will most likely be errors.
The methods will exist, but the data will not
static_cast, as we said is safe for built in values.
But does not checking for classes in a hierarchy.
And is not the way to go.
dynamic_cast
is for this purpose
It does a run time check to see if the proposed cast is safe
It returns a pointer to the class instance if it is
It returns a null pointer if it is not.
Take a look at
slice.cpp
.