Polymorphism: Embracing Diversity in Functions

Polymorphism is the ability of an entity to take on different forms. In the realm of programming, particularly in C++, this refers to the capability of a function to be used in different ways.

Virtual Functions: Unleashing Dynamic Functionality

A virtual function is a member function of a class that opens up a world of dynamic possibilities. Here are the key aspects of virtual functions:

  • Override Flexibility: A virtual function can be overridden in its derived classes, allowing for customization.
  • Declaration Marker: It is declared with the keyword 'virtual' to signify its dynamic nature.
  • Runtime Resolution: The call to a virtual function is resolved at runtime, enabling dynamic dispatch.

Example:

#include <iostream>
using namespace std;

class Parallelogram {
protected:
    int width, height, ar;
public:
    void set_values(int a, int b) {
        width = a;
        height = b;
    }
    // Creating a virtual function
    virtual int area() {
        ar = width * height;
        cout << "Area of parallelogram is " << ar << "\n";
    }
};

class Rectangle : public Parallelogram {
public:
    // Overriding the area function in a different way
    int area() {
        ar = width * height;
        cout << "Area of rectangle is " << ar << "\n";
    }
};

class Triangle : public Parallelogram {
public:
    int area() {
        ar = width * height / 2;
        cout << "Area of triangle is " << ar << "\n";
    }
};

int main() {
    Parallelogram *parallel, p;
    Rectangle rect;
    Triangle trgl;

    parallel = &p;
    parallel->set_values(3, 2);
    parallel->area();

    parallel = &rect;
    parallel->set_values(4, 5);
    parallel->area();

    parallel = &trgl;
    parallel->set_values(6, 5);
    parallel->area();

    return 0;
}

Output:

Area of parallelogram is 6
Area of rectangle is 20
Area of triangle is 15

In this example, the virtual function area() in the base class Parallelogram allows for different implementations in its derived classes (Rectangle and Triangle). The output showcases the dynamic behavior, emphasizing the versatility of polymorphism.

Next Post Previous Post
No Comment
Add Comment
comment url