Cast (Base -> Derived)

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
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.
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.