Zone Of Makos

Menu icon

Polymorphism in C++

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different types to be treated as objects of a common base type. In C++, polymorphism is achieved through the use of virtual functions and function overriding. It enables you to write code that can work with objects of different derived classes through a common interface, providing flexibility and extensibility in your code. In this lesson, we'll explore how polymorphism is implemented in C++ and how it can be used to write more flexible and maintainable code.

Virtual Functions

In C++, a virtual function is a member function of a base class that is declared using the virtual keyword. When a virtual function is overridden in a derived class, the function call is resolved at runtime based on the actual type of the object. This allows you to call the derived class's implementation of the function through a pointer or reference of the base class, achieving polymorphic behavior.


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

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

class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing a rectangle." << endl;
    }
};

int main() {
    Shape* shapePtr;

    Circle circle;
    Rectangle rectangle;

    shapePtr = &circle;
    shapePtr->draw();    // Calls the draw() function of Circle class

    shapePtr = &rectangle;
    shapePtr->draw();    // Calls the draw() function of Rectangle class

    return 0;
}

Polymorphism and Function Overriding

Function overriding is the process of providing a different implementation of a virtual function in a derived class. When a derived class overrides a virtual function from the base class, the function call is resolved based on the actual type of the object, allowing for polymorphic behavior. This means that you can treat objects of different derived classes as objects of the base class, and still call the appropriate implementation of the function based on the object's actual type.

Conclusion

Polymorphism is a powerful feature in C++ that allows objects of different types to be treated as objects of a common base type. It is achieved through virtual functions and function overriding. Polymorphism enables you to write code that can work with objects of different derived classes through a common interface, providing flexibility and extensibility in your code. By utilizing polymorphism effectively, you can write more flexible and maintainable C++ code. In the next lesson, let's learn a quite advanced concept called 'templates'.