Search code examples
c++abstract-class

abstract class and virtual functions


Would this class be considered an abstract class because it has one virtual function? I was still able to create an Animal object and call getFoodCost();

I thought abstract classes cannot be instantiated. Does this mean objects can have virtual functions and not be considered abstract class?

class Animal
{
public:
    Animal();
    int getBabies();
    double getFoodCost();
    virtual double getPayOff();
    int getQty();

    void incAge();
    void setAge(int);

protected:
    int counter=0;
    int age;
    int cost;   
};

Solution

  • Would this class be considered an abstract class because it has one virtual function? I was still able to create an Animal object and call getFoodCost();

    No. In C++, "Abstract Class" usually refers to a class with a pure virtual function:

    class Abstract {
    public:
        virtual void PureVirtual() = 0; // no implementation
    };
    
    class NotAbstract {
        virtual void NotPureVirutal() {
            // Some implementation
        }
    };
    

    I thought abstract classes cannot be instantiated.

    Yes, that is correct. This is because abstract classes have functions with no required implementation. It has no way to instantiate an instance directly. It uses inheritance and pointers/references to refer to an abstract class.

    Does this mean objects can have virtual functions and not be considered abstract class?

    Yes. Again, abstract classes are classes that have pure virtual functions. This is different from a regular virtual function. As discussed above, pure virtual functions have no required implementation. Regular virtual functions, on the other hand, are required to have an implementation associated with them, so they can be instantiated.