Cpp Polymorphism

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common base class. In C++, polymorphism is primarily achieved through two mechanisms: function overloading and virtual functions. I'll explain these concepts in detail with code examples.

1. Function Overloading:

        
#include <iostream>

class Shape {
public:
    void draw() {
        std::cout << "Drawing a generic shape" << std::endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() {
        std::cout << "Drawing a square" << std::endl;
    }
};

int main() {
    Shape s;
    Circle c;
    Square sq;

    s.draw();  // Calls the draw function of the Shape class
    c.draw();  // Calls the draw function of the Circle class
    sq.draw(); // Calls the draw function of the Square class

    return 0;
}
        
    

In this example, we have a base class Shape and two derived classes Circle and Square. Each class has its own draw method, and when you call draw on an object, the appropriate version of the function is called based on the object's type.

2. Virtual Functions:

        
#include <iostream>

class Shape {
public:
    virtual void draw() {
        std::cout << "Drawing a generic shape" << std::endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        std::cout << "Drawing a circle" << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() {
        std::cout << "Drawing a square" << std::endl;
    }
};

int main() {
    Shape s;
    Circle c;
    Square sq;
    
    Shape* shapes[] = {&s, &c, &sq};
    
    for (int i = 0; i < 3; i++) {
        shapes[i]->draw(); // Calls the appropriate draw function based on the object's actual type
    }

    return 0;
}
        
    

In this example, we've marked the draw function in the Shape class as virtual. When we call draw on an array of Shape pointers that point to objects of different derived classes, the correct version of the function is called based on the actual type of the object. This is runtime polymorphism or dynamic binding, and it's a key feature of C++ polymorphism.

In summary, C++ polymorphism allows you to work with objects of different derived classes through a common base class interface, and the appropriate function is called at either compile time (function overloading) or runtime (virtual functions) based on the object's type. This flexibility simplifies code and promotes reusability and maintainability in object-oriented programming.