Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should static_cast<Derived *>(Base pointer) give compile time error?

Tags:

c++

casting

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?
}
like image 477
sandeep Avatar asked Mar 18 '10 10:03

sandeep


People also ask

What happens when you perform a static_cast?

C-style casts also ignore access control when performing a static_cast , which means that they have the ability to perform an operation that no other cast can.

What is the difference between static_cast and dynamic_cast?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.

Is reinterpret cast compile time?

The dynamic cast is the only that needs to be "calculated" in run-time. All other casts are calculated in compile-time. The machine code for a static_cast is a fixed function based on the type you are casting FROM and TO. For reinterpret_cast , the machine code can be resolved in compile-time as well.

Why do we need static_cast in C++?

In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.


1 Answers

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!

like image 113
Abhay Avatar answered Oct 14 '22 07:10

Abhay