I'm wondering whether situation exists where casting is completely necessary.
I'm talking here about casts between classes, not basic types.
Is casting (be it C++ style like static_cast
or dynamic_cast
, or plain C-style cast) a code smell? I can see how sometimes it's helpful, but I think it can also be avoided. Does casting break any OOP rules?
If by code smell you mean that it should raise a flag in a code review, then they are a code smell. If you mean that they should never appear in code, then no, there are some fine uses of casts.
For an interesting example (I always find type erasure interesting), take a look at the implementation of boost::any
where dynamic_cast
is required to safely read from the stored value (unlike union
s where you must guess the type and are limited)
Sketch:
struct any_base {
virtual ~any_base() {}
};
template <typename T>
struct any_data : any_base {
T value;
any_data( T const & value ) : value(value) {}
};
struct any {
any_base * data;
any() : data() {}
~any() { delete data; }
template <typename T>
any( T const & v ) : data( new any_data<T>(v) {}
}
template <typename T>
T any_cast( any const & a ) {
any_base<T> * p = dynamic_cast< any_base<T>* >( a.data );
if ( !p ) throw invalid_cast();
return *p;
}