I have some question related to using static_cast.
Suppose I have 2 classes base and derived and I want to cast base type to derived.
Of course I can use dynamic_cast.
But I can also use static_cast,but it will do unsafe casting. What does mean 'unsafe' here?What can happen?
class Base
{
};
class Child1 : public Base
{
std::string name;
std::string description;
};
class Child2 : public Base
{
int year;
float average_score;
};
You don't need to cast from Child1* or Child2( to Base* because a Child1 is a Base and a Child2 is a Base through polymorphism.
How can cast from a Base* to a Child1* or a Child2*?
If you use RTTI, the compiler can "know" what type your Base* actually points to. dynamic_cast can be used to detect an appropriate pointer.
You can bypass that force the language to make a Base* a Child2* with static_cast. This is unsafe because Base* may in fact be a Child1*. If you treat a Child1 as a Child2, you'll corrupt the state of your app because the memory layouts are different.
dynamic_cast will return a null pointer if the cast fails (because the argument is not derived from the template
parameter); the static_cast never fails, even if the cast is nonsensical.