Having gotten comfortable with the idea of basic classes and encapsulation, I\'ve launched myself towards understanding polymorphism, but I can\'t quite figure out how to ma
You will need to pass a reference instead of a copy:
void speakTo(Animal& animal) {
animal.speak();
}
You cannot pass an Animal
object to the derived class function because you cannot create an object of Animal
class et all, it is an Abstract class.
If an class contains atleast one pure virtual function(speak()
) then the class becomes an Abstract class and you cannot create any objects of it. However, You can create pointers or references and pass them to it.
You can pass an Animal
pointer or reference to the method.
void speakTo(Animal* animal)
{
animal->speak();
}
int main()
{
Animal *ptr = new Dog();
speakTo(ptr);
delete ptr; //Don't Forget to do this whenever you use new()
return 0;
}