Run-time polymorphism, also known as dynamic polymorphism, occurs when a function call to a derived class object is resolved at runtime. It allows for behavior that varies depending on the type of object being referred to at runtime.
virtual
keyword.#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Some generic animal sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Barking" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Meowing" << endl;
}
};
int main() {
Animal* a1 = new Dog();
Animal* a2 = new Cat();
a1->sound(); // Output: Barking
a2->sound(); // Output: Meowing
delete a1;
delete a2;
return 0;
}