0

How to avoid Copy constructor doing object slicing

Refer code below: I have reference to base class and hence it should not result into object slicing. But it seems slicing is done due to copy constructor. How can we avoid this? https://sololearn.com/compiler-playground/cO9TSqCIFbma/?ref=app

3rd Apr 2025, 7:14 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Antworten
+ 3
don't use auto, it resolves to Animal. you want Animal&. or you can use auto&. This resolve to Animal& void TestMethod(Animal& animal) { Animal& copiedAnimal = animal; copiedAnimal.display(); }
3rd Apr 2025, 10:52 AM
Bob_Li
Bob_Li - avatar
+ 2
Thanks Bob_Li
3rd Apr 2025, 11:34 AM
Ketan Lalcheta
Ketan Lalcheta - avatar