+ 1

slicing with reference

https://www.sololearn.com/en/compiler-playground/cwScl8LufuMj Refer code. I thought slicing does not happen due to base class reference taken into print method argument and hence it should print "No Name" and "Abc" respectively. Why it is printing "No Name" twice? It was expected to print "No Name" twice if print was like print(Entity ent).

8th Sep 2024, 12:29 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Réponses
+ 4
Ketan Lalcheta is it this code? (Your link fails to display in my Sololearn Android app) https://sololearn.com/compiler-playground/cwScl8LufuMj/?ref=app perhaps getName was not getting overridden? Declare the base class method as virtual. class Entity { public: virtual string getName() { return "No Name"; } };
8th Sep 2024, 12:36 PM
Bob_Li
Bob_Li - avatar
+ 1
yes. Thanks. Virtual was missed..!
8th Sep 2024, 12:41 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
the rules of inheritance simply state that you'll get the right function for the type of the object you run it on. when you assign a derived object to a base class object, only members of the base class are copied to the new object; it couldn't be any other way, if you think of it ( slicing ). even if you, store a reference ( or pointer ) to the derived object in a base class reference ( or pointer ), it still refers ( or points ) to the original object ( this uses the fact that references ( or pointer ) to objects all look alike). in order to have the derived versions of member functions called through a base class reference ( or pointer ), you must declare the functions virtual. which will expose exactly the behavior you would like to see.
9th Sep 2024, 10:01 AM
MO ELomari
MO ELomari - avatar