Can functions accept abstract base classes as arguments?

后端 未结 2 689
天命终不由人
天命终不由人 2020-12-30 02:10

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

2条回答
  •  长情又很酷
    2020-12-30 02:56

    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;
    }
    

提交回复
热议问题