Example
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Overriding base class function
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
int main() {
Animal* a1;
Dog d;
Cat c;
a1 = &d;
a1->sound(); // Calls Dog's sound()
a1 = &c;
a1->sound(); // Calls Cat's sound()
return 0;
}
Output
Explanation
-
Animal is a base class that includes virtual sound function.
-
Derived classes Dog and Cat use the same function by using virtual keyword.
-
Our base class pointer (Animal* a1) is pointed to both Dog and Cat objects in main.
Due to the virtual nature of this function, the call a1->sound() is not resolvable at compile-time (but only at runtime).
-
When a1 says to the Dog what it sounds like, it calls to the Dog what it sounds like.
Instead, when a1 points at a Cat, it calls the sound () of Cat.
When a1 is pointing at a Cat, then it calls the sound() of Cat.
This demonstrates Function Overriding in C++ as a form of Runtime Polymorphism.
If you found this post useful:
⮕ Share it with others who might benefit.
⮕ Leave a comment with your thoughts or questions—I’d love to hear from you.
⮕ Follow/Subscribe to the blog for more helpful guides, tips, and insights.
Comments
Post a Comment