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?
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:
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.
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.
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.
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.
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