15

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?
}
MrSlippers
  • 459
  • 1
  • 6
  • 14
sandeep
  • 205
  • 1
  • 3
  • 5
  • Use the `010` button or indent by 4 spaces for code markup. – Georg Fritzsche Mar 18 '10 at 10:30
  • @sandeep, is there any intended purpose to the `cout<<` statements in those constructors? As far as I see, they are unrelated to the question, and would be better removed. – Peter Alexander Mar 18 '10 at 10:44
  • 1
    It should be noted that, even if this code snippet will compile fine, it will have an **undefined behavior**. You are making the promise to the compiler that `a` is pointing to a B object, and you are lying to your compiler. Nasal demons are on their way. – Ad N Nov 22 '13 at 15:01
  • `A *a=new A(); B * b=static_cast(a);` is not a good practice. It will give you some nasty errors. – Taitai Nov 03 '18 at 00:44

2 Answers2

19

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!

Abhay
  • 7,092
  • 3
  • 36
  • 50
  • What do you mean by "dynamic_cast may fail or not" ? Do you mean that there is uncertainty about the fact that dynamic_cast will fail in the example above ? Or do you mean that it will always fail ? – ibizaman Apr 09 '13 at 05:20
  • @ibizaman: There is no uncertanity here. Infact it will tell you when it failed and when it did not fail. I think if you read the complete sentence it should make sense. – Abhay Apr 27 '13 at 02:07
  • indeed, it was just to be sure :) – ibizaman Apr 27 '13 at 06:17
15

It doesn't give a compile time error because the cast could very-well be valid, and you would often do it in practice, e.g.:

A* a = new B;
B* b = static_cast<B*>(a); // OK

In your code, as far as the compiler is concerned, you are doing the same thing. It cannot know that the cast would be invalid, so it allows it at compile time. At run time however, you're going to get some nasty errors as soon as you try to use a feature of B on an instance of A.

Peter Alexander
  • 53,344
  • 14
  • 119
  • 168