Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it well-defined behavior to pass a subclass object by value to a function taking a superclass object?

I have looked at the related questions such as here and here about this topic, and they all describe object slicing, but none of them address whether it is safe, reliable and predictable.

Is there a guarantee from either the standard or the compiler, that if I pass a subclass object by value to a method which wants a superclass, the parts that are sliced off are exactly the members of the subclass, and I will be able to use the sliced superclass object without any concerns about undefined behavior?

like image 206
merlin2011 Avatar asked Apr 16 '14 20:04

merlin2011


People also ask

How to display the subclass of an object in a class?

For example, a subclass can call a superclass disp method to implement the display of the superclass part of the object. Then the subclass adds code to display the subclass part of the object:

How do you refer to a subclass of a superclass?

First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed.

Can subclasses override superclass methods?

Subclasses can override superclass methods to support the greater specialization defined by the subclass. Because of the relationship that a subclass object is a superclass object, it is often useful to call the superclass version of the method before executing the specialized subclass code.

What are the advantages of subclass reference in Java?

Advantage : By using subclass reference, we will have access to both parts (methods and variables) of the object defined by the superclass or subclass. For example, we can call setHeight (int newValue) method or speedUp (int increment) method using MountainBike reference in above first example.


1 Answers

Yes, it is safe, reliable, and predictable, because it is well defined by the standard (it will just copy construct a base class object from the derived class object).

But no, it is not safe, it should not be relied on, and generally be treated as unpredictable, because your readers won't know what's going on. This will trigger a lot of bugs when others try to modify your code later (including your own future self). It is basically a no-no, much in the same way as the goto statement, which is perfectly well defined, reliable, and predictable as well.

like image 165
cmaster - reinstate monica Avatar answered Oct 13 '22 11:10

cmaster - reinstate monica