-
Notifications
You must be signed in to change notification settings - Fork 71
Virtual Functions
Terry Griffin edited this page Nov 27, 2018
·
7 revisions
View links and examples below:
-
https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/
-
https://www.geeksforgeeks.org/virtual-functions-and-runtime-polymorphism-in-c-set-1-introduction/
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;
}
};
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].
© 2018 Terry Griffin