I am reviewing C++ casts operator and I have the following doubt:
for polymorphic classes
- I I should use
polymorphic_cast - I should never use of
static_castsince down-casting might carry to undefined behavior. The code compiles this case anyway.
Now suppose that I have the following situtation
class CBase{};
class CDerived : public CBase{};
int main( int argc, char** argv ){
CBase* p = new CDerived();
//.. do something
CDerived*pd = static_cast<CDerived*>( p );
}
Since there is no polymorphism involved I will not use polymorphic_cast and the code will not even compile.
If at some point, someone introduces some virtual functions in the inheritance tree and I am now aware of it so I am in danger: how can I realize it?
I should move to polymorphic_cast to avoid any risk, but the code will be still compiling without any notification.
What do you do to realize about such kind of changes or prevent these case?
Thanks
AFG
Background you didn’t include – boost has
polymorphic_castas a wrapper arounddynamic_cast<>that throws when the cast fails.static_cast<>is fine if you’re certain that the data is of the type you’re casting to… there is no problem with or without virtual members, and the code you include saying it won’t compile will compile and run just fine as is.I guess you’re thinking about the possibility to accidentally cast to another derived class? That’s the utility/danger of casting, isn’t it? You can add a virtual destructor then use dynamic_cast<>, as strictly speaking RTTI is only available for types with one or more virtual functions.
Code written with static_cast<> will continue to handle the same type safely irrespective of the introduction of virtual functions… it’s just that if you start passing that code other types (i.e. not CDerived or anything publicly derived therefrom) then you will need the dynamic_cast<> or some other change to prevent incompatible operations.