Cast (Base -> Derived)

Mar 14, 2014 at 10:19am
Why can not I convert the object of a base class to a derived class without using pointers?

1
2
3
4
5
Base o; 
Derived i = (Derived)o; /*/ Error /*/

Base* o; 
Derived* i = (Derived*)o; /*/ Ok /*/
Last edited on Mar 14, 2014 at 10:20am
Mar 14, 2014 at 10:46am
Because you should almost never do that. That is one of the reasons why C-style casts are bad. It should not let you do that even with pointers.

Best you can do is to provide Derived class with constructor which takes Base class reference as a parameter.
Mar 14, 2014 at 12:11pm
Because your object o ISN'T an object of type Derived. What you're trying to do would result in an object in an undefined state. Of course, you could write your own type conversion operator, to return a properly-constructed object of type Derived, if you like.
Topic archived. No new replies allowed.