Can functions accept abstract base classes as arguments?

后端 未结 2 677
天命终不由人
天命终不由人 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:54

    You will need to pass a reference instead of a copy:

    void speakTo(Animal& animal) {
        animal.speak();
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题