Polymorphism means "many forms". In C++, it allows functions or methods to behave differently based on the object that calls them. This helps to write flexible and reusable code.
This allows a derived class to override a function from the base class. The function to call is decided at run time based on the object type.
#include <iostream> using namespace std; class Animal { public: virtual void sound() { cout << "Animal makes a sound" << endl; } }; class Dog : public Animal { public: void sound() override { cout << "Dog barks" << endl; } }; class Cat : public Animal { public: void sound() override { cout << "Cat meows" << endl; } }; int main() { Animal* animal; Dog myDog; Cat myCat; animal = &myDog; animal->sound(); // Calls Dog's sound() animal = &myCat; animal->sound(); // Calls Cat's sound() return 0; }
sound()
is declared as virtual
in the base class Animal
.animal
points to different derived objects (Dog
, Cat
).sound()
function is called based on the actual object, not the pointer type.virtual
functions and inheritance.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!