C++ virtual Keyword
Example
Call the Dog version of a method through an Animal pointer:
class Animal {
public:
virtual void animalSound() {
cout << "The animal makes a sound\n";
}
};
class Dog : public Animal {
public:
void animalSound() override {
cout << "The dog says: bow wow\n";
}
};
int main() {
Dog myDog;
Animal* a = &myDog;
a->animalSound();
return 0;
}
Definition and Usage
The virtual keyword specifies that a class method is virtual. A virtual method can be overridden (replaced) by a method with the same name in a child class.
When you call a virtual method through a pointer to the parent class, C++ checks the actual object, and runs its version of the method. In the example above, a points to a Dog, so the Dog version runs. Without virtual, the Animal version would run, and the output would be The animal makes a sound.
Use virtual only in the parent class. In the child class, you can write override after the method (optional, but recommended).
Related Pages
Read more about virtual functions in our C++ Virtual Functions Tutorial.
Read more about polymorphism in our C++ Polymorphism Tutorial.