Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does static_cast allow downcasts when logically it should refuse them for safety purposes or static_cast is not about safety?

Tags:

c++

In the following example the compiler accepts the static_cast downcast resulting in undefined behavior while I thought static_cast was all about safety (that C-style casts were unable to provide).

#include <iostream>

class Base {
public:
    int x = 10;
};
class Derived1: public Base 
{
public:
    int y = 20;

};
class Derived2 : public Base 
{
public:
    int z = 30;
    int w = 40;

};

int main() {

    Derived1 d1;

    Base* bp1 = static_cast<Base*>(&d1);
    Derived2* dp1 = static_cast<Derived2*>(bp1);

    std::cout << dp1->z << std::endl; // outputs 20
    std::cout << dp1->w << std::endl; // outputs random value
}
like image 638
Soulimane Mammar Avatar asked Nov 29 '22 05:11

Soulimane Mammar


1 Answers

You use dynamic_cast only really when you are not sure if the cast is going to succeed and you catch exceptions or check for nullptr. However if you are sure your downcasting is going to succeed, the language allows you to use static_cast (which is cheaper). If you were wrong, that is your problem. In an ideal world every cast would succeed in 100% of the time. But we don't live in an ideal world. It's a bit like array subscript. arr[5] means "I am absolutely sure this array has at least 6 elements. Compiler doesn't need to check". If your array was smaller than you expected, that's again your problem.

like image 155
Ayxan Haqverdili Avatar answered Dec 18 '22 07:12

Ayxan Haqverdili