Example
In C++, function overriding happens when a derived class defines a function with the same name as a base class function.
-
Unless the base class method is specified as virtual, the compiler engages in early binding (compile-time decision).
- This implies that the base class version will be invoked even when the pointer points to an object of the derived classes.
- This leads to a lack of real-time polymorphism occurring.
Code Example
#include <iostream>
using namespace std;
class Animal {
public:
void sound() { // Not virtual
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* a1;
Dog d;
a1 = &d;
a1->sound(); // Calls Animal's version (not Dog's)
return 0;
}
Output
Short Explanation
-
In this instance, Dog suppresses the method sound.
-
But since
sound()
inAnimal
is not virtual, the calla1->sound()
is resolved at compile time. -
Therefore, the base version (Animal makes a sound) is run.
-
In order to implement runtime polymorphism and have it print out Dog barks, we need to declare a base class method as virtual.
⮕ 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