If I have a C++ function/method, for example:
getSound(Animal a){
a.printSound();
}
and then pass it a Dog object that extends the class Animal but overrides Animal’s printSound() method, is there a way of using Dog’s printSound() within getSound()?
I have tried making printSound() in the Animal class definition virtual, but I am still getting the output of the original printSound().
Thanks in advance.
Making
printSoundvirtual was correct. Change the signature ofgetSoundto take aAnimal&orconst Animal&. By taking anAnimalby value you are constructing a newAnimalfrom yourDog, and that’s just anAnimal, not aDog.