Junior — Middle
How is polymorphism implemented in C++?
sobes.tech AI
Answer from AI
In C++, the mechanism of polymorphism is implemented using virtual functions and inheritance. Polymorphism allows objects of different classes, related by inheritance hierarchy, to respond differently to the same method calls.
To implement polymorphism in C++:
- Declare the method as
virtualin the base class. - Override this method in derived classes.
- When working with pointers or references to the base class, the call to a virtual function will be dynamically bound to the derived class's implementation.
Example:
#include <iostream>
class Animal {
public:
virtual void speak() {
std::cout << "Animal speaks" << std::endl;
}
virtual ~Animal() = default; // virtual destructor
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Woof!" << std::endl;
}
};
int main() {
Animal* animal = new Dog();
animal->speak(); // Outputs: Woof!
delete animal;
return 0;
}
Thus, virtual functions provide dynamic binding and enable polymorphism in C++.