A derived class object can be assigned to a base class object in C++.
Derived d;
Base b = d; // It's Ok
But why can't a base class object be assigned to a derived class object?
Base b;
Derived d = b; //Not Ok. Compiler give an error
Edit:
Sorry, but this question was actually asked durring an interview.
In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
Expanding on @ybo's answer - it isn't possible because the instance you have of the base class isn't actually an instance of the derived class. It only knows about the members of the base class, and doesn't know anything about those of the derived class.
A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB , and ClassB is derived from ClassA , ClassC inherits the members declared in ClassB and ClassA .
similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.
Inheritance is an "is-a" relationship, but it's one-way only.
If you have e.g.
struct Base { /* ... */ };
struct Derived : Base { /* ... */ };
Then Derived
is a Base
, but Base
is not a Derived
.
That's why you can assign or initialize a base-class instance with a derived object (but beware of object slicing), but not the other way around.
A derived object is a base object, with additional information.
You can initialize a complete base object from the base part of a derived object, no problem.
But if you want to construct a derived object from just a base object, what should the additional information be initialized with?
If you want to provide defaults for that additional information, you can do so by declaring a Derived(Base const &)
constructor. But since it does not work in the general case, it isn't done for you.
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