0
We can assign Derived Class Object to Base Class Object. But why can't we do the reverse?
class Base { }; class Derived : public Base { }; int main( ) { Base obj1; Derived obj2; obj1 = obj2; // Works obj2 = obj1; // Won't Work return 0; }
2 Answers
+ 2
Say you have a superclass Animal, and a subclass Dog. A Dog is an Animal, but not every Animal is a Dog.
In your example, every Derived is a Base, so you can store obj2 into obj1. But not every Base is a Derived, so you cannot store obj1 into obj2.
+ 2
Because all derived classes contain all of the members of the base class. The base class, however, does not contain all of the members of the derived classes.
If you had the base class Animal and two derived classes Dog and Cat, you could not assign a Cat object as an animal, because it may have the function meow, which does not exist in animal. You can assign an Animal object as a Cat though and then call for example the function jump, which is something also a dog can do.