5.2) Function overriding

Function overriding is a concept in C++ that allows a subclass to provide a specific implementation for a function that is already defined in its base class. This enables polymorphism, where different classes can have the same function signature but provide different implementations.

Here’s a detailed explanation of function overriding with code examples:

1. Base and Derived Classes


Let’s start with a base class that defines a virtual function, which can be overridden by its derived classes.

#include <iostream>

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

2. Function Overriding


Now, create a derived class that overrides the virtual function of the base class.

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

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

3. Using Overridden Functions


You can create objects of the derived classes and call the overridden function. The function called depends on the actual type of the object.

int main() {
    Circle circle;
    Square square;

    Shape* shapePtr1 = &circle;
    Shape* shapePtr2 = &square;

    shapePtr1->draw();  // Calls Circle's draw()
    shapePtr2->draw();  // Calls Square's draw()

    return 0;
}

Output:

Drawing a circle
Drawing a square

4. Virtual Keyword


To enable function overriding, you need to declare the function in the base class as virtual. This tells the compiler that the function can be overridden by derived classes.

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

5. Dynamic Polymorphism


The concept of function overriding is crucial for achieving dynamic polymorphism. When you call a virtual function using a base class pointer or reference, the function that gets executed is determined at runtime based on the actual object type.

int main() {
    Shape* shapes[2];
    Circle circle;
    Square square;

    shapes[0] = &circle;
    shapes[1] = &square;

    for (int i = 0; i < 2; ++i) {
        shapes[i]->draw();
    }

    return 0;
}

Output:

Drawing a circle
Drawing a square

Function overriding and virtual functions are crucial in enabling polymorphism and providing a way to write more flexible and extensible code. By defining a common interface in the base class and allowing derived classes to provide their implementations, you can achieve dynamic behavior at runtime.

Leave a Reply