C++ Polymorphism

Polymorphism is one of the four fundamental principles of object-oriented programming (OOP) along with encapsulation, inheritance, and abstraction. It is the ability of an object to take on many forms. In C++, polymorphism can be achieved in two ways: function overloading and virtual functions.

Function Overloading

Function overloading is a feature in C++ where multiple functions can have the same name but different parameters. The compiler determines which function to call based on the number and type of arguments passed.

1#include <iostream> 2using namespace std; 3 4class Shape { 5 public: 6 int area(int length) { 7 return length * length; 8 } 9 10 int area(int length, int breadth) { 11 return length * breadth; 12 } 13}; 14 15int main() { 16 Shape s; 17 cout << "Area of Square: " << s.area(5) << endl; 18 cout << "Area of Rectangle: " << s.area(5, 10) << endl; 19 return 0; 20}

Output:

1Area of Square: 25 2Area of Rectangle: 50

Virtual Functions

Virtual functions are member functions that can be redefined in derived classes. They are used to achieve runtime polymorphism. The key feature of virtual functions is that they are resolved dynamically at runtime.

1#include <iostream> 2using namespace std; 3 4class Shape { 5 public: 6 virtual int area() { 7 return 0; 8 } 9}; 10 11class Square: public Shape { 12 private: 13 int length; 14 public: 15 Square(int length) { 16 this->length = length; 17 } 18 19 int area() { 20 return length * length; 21 } 22}; 23 24class Rectangle: public Shape { 25 private: 26 int length, breadth; 27 public: 28 Rectangle(int length, int breadth) { 29 this->length = length; 30 this->breadth = breadth; 31 } 32 33 int area() { 34 return length * breadth; 35 } 36}; 37 38int main() { 39 Square s(5); 40 Rectangle r(5, 10); 41 Shape *shape; 42 shape = &s; 43 cout << "Area of Square: " << shape->area() << endl; 44 shape = &r; 45 cout << "Area of Rectangle: " << shape->area() << endl; 46 return 0; 47}

Output:

1Area of Square: 25 2Area of Rectangle: 50

Polymorphism is a key concept in C++ and it allows objects to have different forms. The use of polymorphism provides a way to write more flexible and reusable code, which is one of the core goals of object-oriented programming.