Output of following program?
This is Derived class This is Base class
This is Base class This is Derived class
This is Base class This is Base class
(D) Compiler Error
Explanation: Note that an object of Derived is passed in describe(d), but print of Base is called. The describe function accepts a parameter of Base type.
This is a typical example of object slicing, when we assign an object of derived class to an object of base type, the derived class object is sliced off and all the data members inherited from base class are copied. Object slicing should be ovoided as there may be surprising results like above. As a side note, object slicing is not possible in Java. In Java, every non-primitive variable is actually a reference.
Quiz of this Question