C++ Virtual Functions
C++ Virtual Functions
A virtual function is a member function in the base class that can be overridden in derived classes.
Virtual functions are a key part of polymorphism in C++. They let different objects respond differently to the same function call.
Why Use Virtual Functions?
Without virtual, C++ decides which function to call based on the pointer type, not the actual object type.
With virtual, it checks the actual object the pointer is pointing to.
Or to put it even more simply:
- Without
virtual: the base function runs, even if the object is from a child class. - With
virtual: the child's version runs, like you expect.
Without Virtual Function
Example (No virtual keyword)
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound\n";
}
};
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow\n";
}
};
int main() {
Dog myDog;
Animal* a = &myDog; // A pointer to the base class (Animal), pointing to a Dog
a->animalSound(); // animalSound() is not virtual, so this calls Animal's version
return 0;
}
Try it Yourself »
This is the Animal and Dog example from the Polymorphism chapter. But this time, we call animalSound() through a pointer to the base class.
Even though a points to a Dog, it still calls Animal's animalSound(), because the function is not virtual.
With Virtual Function
Example (With virtual keyword)
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(); // The dog says: bow wow
return 0;
}
Try it Yourself »
Now it works! Because animalSound() is virtual, the call uses the actual object's function and not just the pointer type.
- Use
virtualonly in the base class - Use
override(optional, but recommended) in the derived class for clarity
The -> Operator in C++
You learned about the -> operator in The this Pointer chapter. That is why the examples above use ->: a is a pointer, not an object.
The -> operator is used to access members (like functions or variables) through a pointer.
It's a shortcut for writing (*pointer).member:
Dog myDog;
Animal* a = &myDog;
a->animalSound(); // Same as (*a).animalSound();
Tip: If you are using a pointer to an object, use -> to access its members.