Is it possible and why one would want to do it?
class Foo;
class Bar;
......
Foo foo;
Bar bar = static_cast<Bar>(foo);
Normally static_cast is used with numeric types and pointers, but can it work with user defined data types, a.k.a classes?
The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.
static_cast only allows conversions like int to float or base class pointer to derived class pointer. reinterpret_cast allows anything, that's usually a dangerous thing and normally reinterpret_cast is rarely used, tipically to convert pointers to/from integers or to allow some kind of low level memory manipulation.
Conversion functions define conversions from a user-defined type to other types. These functions are sometimes referred to as "cast operators" because they, along with conversion constructors, are called when a value is cast to a different type.
Since C++ is 99% backwards-compatible with C, most C source code can be compiled as C++ source code and will work, and in that scenario, static_cast could be part of the code and would compile.
Bar bar = static_cast<Bar>(foo);
This cast will fail. Foo
and Bar
are incompatible types, unless atleast one of the following is true:
Foo
is derived from Bar
, OrBar
has a constructor that takes Foo
, OrFoo
has a user-defined conversion to Bar
. The bigger question here is not whether it will cast successfully or not. The bigger and the actual question should be: what do you want to get out of such cast? Why would you want to do such a thing in the first place? What is it supposed to do? I mean, how would the Bar
object be initialized from Foo
object?
The sensible way to convert one type to another is one of the following ways:
Either define Foo
as:
class Foo : public Bar
{
//...
};
Or define Bar
as:
class Bar
{
public:
Bar(const Foo &foo); //define this constructor in Bar!
};
Or provide a conversion function in Foo
as:
class Foo
{
public:
operator Bar(); //provide a conversion function Foo to Bar!
};
Here's the rule:
The expression static_cast<T>(e)
is valid if and only if the following variable definition is valid
T x(e);
where x
is some invented variable.
So, in general, two unrelated types cannot be cast to one another. However, if one type is derived from the other, or when one defines a conversion function to the other, or has a constructor taking a single argument of the other type - in these cases static_cast will be well-defined.
Does it ever make sense? For example, if T defines a constructor that takes a single U and the constructor is explicit
then static_cast<T>(e)
where e is of type U would make perfect sense
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With