Understanding Function Overriding in C++

Function overriding is a concept in C++ where a function defined in the base class is redefined in the derived class. The derived class function essentially replaces or overrides the function in the base class. It's important to note that the arguments and return type of the overridden function remain the same.

Example:

#include <iostream>
using namespace std;

class Arithmetic {
protected:
    int a, b, sum, sub, mul, div;

public:
    void setValues(int x, int y) {
        a = x, b = y;
    }

    virtual int performOperation() {
        sum = a + b;
        cout << "Addition of two numbers is " << sum << "\n";
    }
};

class Subtract : public Arithmetic {
public:
    int performOperation() override {
        sub = a - b;
        cout << "Difference of two numbers is " << sub << "\n";
    }
};

class Multiply : public Arithmetic {
public:
    int performOperation() override {
        mul = a * b;
        cout << "Product of two numbers is " << mul << "\n";
    }
};

class Divide : public Arithmetic {
public:
    int performOperation() override {
        div = a / b;
        cout << "Division of two numbers is " << div << "\n";
    }
};

int main() {
    Arithmetic *arith, p;
    Subtract subt;
    Multiply mult;
    Divide divd;

    arith = &p;
    arith->setValues(30, 12);
    arith->performOperation();

    arith = &subt;
    arith->setValues(42, 5);
    arith->performOperation();

    arith = &mult;
    arith->setValues(6, 5);
    arith->performOperation();

    arith = &divd;
    arith->setValues(6, 3);
    arith->performOperation();

    return 0;
}

Output:

Addition of two numbers is 42
Difference of two numbers is 37
Product of two numbers is 30
Division of two numbers is 2

Difference Between Overloading and Overriding:

  • Overloading:

    • Can occur without inheritance.
    • The function name remains the same, but the arguments and return type must differ.
    • Behaves differently based on the arguments passed.
  • Overriding:

    • Occurs when one class is inherited from another.
    • The function name, arguments, and return type remain the same.
    • The derived class function can perform different operations from the base class.
Next Post Previous Post
No Comment
Add Comment
comment url