[ACCEPTED]-Can functions accept abstract base classes as arguments?-abstract-class
Accepted answer
You cannot pass an Animal
object to the derived 8 class function because you cannot create 7 an object of Animal
class et all, it is an Abstract class.
If 6 an class contains atleast one pure virtual 5 function(speak()
) then the class becomes an Abstract 4 class and you cannot create any objects 3 of it. However, You can create pointers 2 or references and pass them to it.
You can 1 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;
}
You will need to pass a reference instead 1 of a copy:
void speakTo(Animal& animal) {
animal.speak();
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.