Please use the format tag to format your code. It's pretty much unreadable otherwise.
Static cast means, "Please convert that thing to to something of this specified type using C++ conversion rules".
In this case, you're playing around with inheritance trees. Step back and look at this example. Let's forget about methods for now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class C
{
public:
long lvar;
};
class DI : base C
{
public:
int ivar;
};
class DD : base C
{
public:
double dvar;
};
|
How do they look in memory?
* C occupies enough space to hold a long. let's say 8 bytes.
* DI needs to hold a long and an int, let's say 12 bytes.
* DD needs to hold a long and a double, let's say 16 bytes.
Let's look at some casts.
1 2 3 4 5 6 7 8 9
|
C *obj = new DI; // create DI, (long + int) 12 bytes
DI *objdi = static_cast<DI*>(obj); // objdi points to a DI, it is a DI so that's ok
objdi->ivar = 7; // this is ok
DD* objdd = static_cast<DD*>(obj); // objdd points to a DI, this is NOT ok, but
// the compiler allows it
objdi->dvar = 7.3; // this is wrong, the assignment overwrites the beyond the end
// of the object and corrupts the following 4 bytes.
|
So, if you
know the correct type being pointed to, you can do a static_cast to the derived class. If you get it wrong, there are no rules to stop you and you'll make a terrible mess.
There is a typesafe downcast, but it can only be used in object oriented programming. Specifically, classes that are used in C++ object orientation have virtual functions, and dynamic_cast can only be used by those.