Polymorphism - RJAE5/2143-OOP GitHub Wiki
Polymorphism
Polymorphism in C++ Object-Oriented Programming refers to the ability of different classes to provide different implementations of the same function or method. It allows objects of different classes to be treated as objects of a common base class, enabling dynamic behavior depending on the type of the object. The two main types of polymorphism in C++ are compile-time polymorphism (method overloading and operator overloading) and run-time polymorphism (method overriding).
Compile-Time Polymorphism
Occurs when the function or operator is selected at compile-time based on the arguments or types involved. This is typically achieved through function overloading or operator overloading.
Run-Time Polymorphism:
Occurs when the function to be executed is determined at runtime based on the actual object type, rather than the type of the pointer or reference. This is achieved using virtual functions and inheritance. It allows the base class pointer or reference to invoke methods from derived class objects dynamically.
Run-Time Polymorphism Example
class Animal
{
public:
// Virtual function to be overridden in derived classes
virtual void sound()
{
std::cout << "Animal makes a sound." << std::endl;
}
};
class Dog : public Animal
{
public:
// Overriding the base class function
void sound() override
{
std::cout << "Dog barks." << std::endl;
}
};
class Cat : public Animal
{
public:
// Overriding the base class function
void sound() override {
std::cout << "Cat meows." << std::endl;
}
};
int main()
{
Animal* animal; // Base class pointer
Dog dog;
Cat cat;
// Demonstrating run-time polymorphism
animal = &dog;
animal->sound(); // Calls Dog's sound()
animal = &cat;
animal->sound(); // Calls Cat's sound()
return 0;
}
Code adapted from ChatGPT
Despite using the same pointer type Animal*, the correct version of sound() is called depending on the actual object type at runtime.
Output:
Dog barks.
Cat meows.
Important Notes
- Run-time polymorphism enables dynamic method dispatch. The method called is determined at runtime based on the actual type of the object, not the type of the reference or pointer.
- Virtual functions are essential for enabling run-time polymorphism in C++.
- Polymorphism allows objects of different types to be treated uniformly, which simplifies code and promotes flexibility and extensibility in object-oriented designs.