Polymorphism
Polymorphism, a key concept in object-oriented programming (OOP), refers to the ability of objects of different classes to be treated as objects of a common base class. This allows for code reuse and enables behavior to be determined at runtime.
In C++, polymorphism is achieved through the use of virtual functions. A virtual function is a member function of a class that can be overridden in a derived class.
To demonstrate polymorphism, let's consider an example involving animals. We have a base class Animal
and two derived classes Dog
and Cat
. Each derived class has its own implementation of the makeSound()
function.
1// Base class
2
3class Animal {
4public:
5 virtual void makeSound() {
6 cout << "The animal makes a sound" << endl;
7 }
8};
9
10// Derived class
11
12class Dog : public Animal {
13public:
14 void makeSound() {
15 cout << "The dog barks" << endl;
16 }
17};
18
19// Derived class
20
21class Cat : public Animal {
22public:
23 void makeSound() {
24 cout << "The cat meows" << endl;
25 }
26};
In the main()
function, we can create objects of type Dog
and Cat
and use a pointer of the base class type Animal
to invoke the makeSound()
function. This is where polymorphism comes into play.
1int main() {
2 Animal* animal;
3 Dog dog;
4 Cat cat;
5
6 // Animal pointer pointing to a Dog object
7 animal = &dog;
8 animal->makeSound(); // Output: The dog barks
9
10 // Animal pointer pointing to a Cat object
11 animal = &cat;
12 animal->makeSound(); // Output: The cat meows
13
14 return 0;
15}
As you can see, when we call the makeSound()
function on the animal
pointer, the appropriate implementation is invoked based on the actual object type. This behavior is determined at runtime, allowing for flexibility in the code.
Polymorphism is a powerful OOP concept that promotes code flexibility, extensibility, and modularity. It allows for the creation of generic code that can operate on objects of different classes as long as they inherit from a common base class.
xxxxxxxxxx
}
using namespace std;
// Base class
class Animal {
public:
virtual void makeSound() {
cout << "The animal makes a sound" << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void makeSound() {
cout << "The dog barks" << endl;
}
};
// Derived class
class Cat : public Animal {
public:
void makeSound() {
cout << "The cat meows" << endl;
}
};