Skip to content

Virtual Functions

Terry Griffin edited this page Nov 27, 2018 · 7 revisions

Under Construction

View links and examples below:

class Animal {
public:
    void /*non-virtual*/ move(void) { 
        std::cout << "This animal moves in some way" << std::endl; 
    }
    virtual void eat(void) = 0;  // Must be overridden
};

// The class "Animal" may possess a definition for eat() if desired.
class Llama : public Animal {
public:
    // The non virtual function move() is inherited but not overridden
    void eat(void) override { 
        std::cout << "Llamas eat grass!" << std::endl; 
    }
};

Abstract classes and pure virtual functions

A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly. A subclass of an abstract class can only be instantiated directly if all inherited pure virtual methods have been implemented by that class or a parent class. Pure virtual methods typically have a declaration (signature) and no definition (implementation) [1].

Sources:

  1. https://en.wikipedia.org/wiki/Virtual_function