Junior — Middle
Could you describe the different types of polymorphism used in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming (OOP), polymorphism allows objects of different classes to be processed through a single interface. The main types of polymorphism:
-
Compile-time (static) polymorphism — determined during compilation.
- Function overloading: multiple functions with the same name but different parameters.
- Operator overloading: defining the behavior of operators for user-defined types.
-
Runtime (dynamic) polymorphism — determined during execution.
- Virtual functions in C++: the base class declares a function as
virtual, and derived classes override it. Calling the function through a pointer or reference to the base class invokes the derived class's version.
- Virtual functions in C++: the base class declares a function as
Example of dynamic polymorphism in C++:
#include <iostream>
class Animal {
public:
virtual void sound() { std::cout << "Some sound" << std::endl; }
};
class Dog : public Animal {
public:
void sound() override { std::cout << "Bark" << std::endl; }
};
void makeSound(Animal& a) {
a.sound();
}
int main() {
Dog d;
makeSound(d); // Outputs "Bark"
return 0;
}
Thus, polymorphism allows writing more flexible and extensible code.