static_cast

Aug 25, 2010 at 8:05am
Hi all,

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?

Thanks.
Last edited on Aug 25, 2010 at 8:05am
Aug 25, 2010 at 8:23am
Consider these classes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.
Aug 25, 2010 at 9:32am
OK...let me see...

Consider I want to do this casting
1
2
3
4
5
Base* b1 = new Child1();
Base* b2 = new Child2();

Child1* c1 = dynamic_cast<Child1*>(b1);
Child2* c2 = static_cast<Child2*>(b2);


What is the difference between Line4 and Line5? What kind of dangerous thing can happen in Line5?

Thanks.
Aug 25, 2010 at 10:11am
Those in your example are fine.
In line 4, c1 points to a Child1.
In line 5, c2 correctly points to a Child2.

The problem is when that you can make a mistake. e.g.
Child2* c3 = static_cast<Child1*>(b2);

c3 will incorrectly point to a Child1, but thinks it points to a Child2. That's the unsafe case.
Last edited on Aug 25, 2010 at 10:11am
Aug 25, 2010 at 12:47pm
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.
Aug 25, 2010 at 4:11pm
Thank you guys very much!!!
Topic archived. No new replies allowed.