The virtual keyword says that a function can be overridden at run-time:
// // g++ virtual.cpp // #include <iostream> using namespace std; class Animal { public: virtual void eat() { std::cout << "I'm eating generic food." << endl; } }; class Cat : public Animal { public: void eat() { std::cout << "I'm eating a mouse." << endl; } }; void func(Animal *a) { a->eat();} int main () { Animal *animal = new Animal; Cat *cat = new Cat; func(animal); func(cat); return 0; }
To enforce that the derived class implements a function the pure virtual function syntax used:
// // g++ virtual.cpp // #include <iostream> using namespace std; class Animal { public: virtual void eat() = 0; // pure virtual function, no function body in the base class. }; class Cat : public Animal { public: void eat() { std::cout << "I'm eating a mouse." << endl; } }; void func(Animal *a) { a->eat();} int main () { Cat *cat = new Cat; func(cat); return 0; }