Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Should static_cast(Base pointer) give compile time error?

class A
{
public:
    A()
    {

    }
};

class B : public  A
{
 public:
     B()
     {
     }
};

int main()
{
    A *a=new A();
    B * b=static_cast<B*>(a);   // Compile Error?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
324 views
Welcome To Ask or Share your Answers For Others

1 Answer

It cannot give compile time error because a Base-Derived relationship can exist at runtime depending on the address of the pointers being casted. static_cast always succeeds, but will raise undefined-behavior if you don't cast to the right type. dynamic_cast may fail or not, actually telling you whether you tried to cast to the right type or not.

So in my opinion, static_cast should be used to downcast only if the design can establish that such a possibility exists. One good example of this is CRTP. So it is logical in some situations but try to avoid it as it is undefined-behavior.

RTTI is not needed for static_cast which might make it theoretically faster, but I will anytime trade-in a dynamic_cast against the undefined behavior that static_cast may cause!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...