We can assign Derived Class Object to Base Class Object. But why can't we do the reverse? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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; }

26th Jan 2017, 3:20 PM
james nyle
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.
26th Jan 2017, 3:24 PM
Álvaro
+ 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.
26th Jan 2017, 3:27 PM
Division by Zero