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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This cast will fail.
FooandBarare incompatible types, unless atleast one of the following is true:Foois derived fromBar, OrBarhas a constructor that takesFoo, OrFoohas a user-defined conversion toBar.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
Barobject be initialized fromFooobject?The sensible way to convert one type to another is one of the following ways:
Either define
Fooas:Or define
Baras:Or provide a conversion function in
Fooas: