Introduction To Function Overriding

 

Function overriding

Redefining a base class function in the derived class

The derived class function overrides the base class function

But the arguments passed are the same

And the return type is also the same


Example:-

#include <iostream>
using namespace std;
 
class arithmetic
{
  protected:
    int a, b, sum, sub, mul, div;
  public:
    void values (int x, int y)
      {
      a=x, b=y;
      }
    virtual int operations ()
      {
      sum= a + b;
      cout<< "Addition of two numbers is "<< sum<<"\n";
      }
};
 
class Subtract: public arithmetic 
{
  public:
//here function overridden
    int operations ()
      {
      sub= a - b;
      cout<< "Difference of two numbers is "<<sub <<"\n";
      }
};
 
class Multiply: public arithmetic
{ 
  public:
//here function overridden
    int operations ()
      {
      mul = a * b;
      cout<< "Product of two numbers is "<< mul<<"\n";
      }
};
 
class Divide: public arithmetic
{ 
  public:
//here function overridden
    int operations ()
      {
      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->values(30,12);
    arith->operations();
 
    arith=&subt;
    arith->values(42,5);
    arith->operations();
 
    arith=&mult;
    arith->values(6,5);
    arith->operations();
 
    arith=&divd;
    arith->values(6,3);
    arith->operations();

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

Overriding occurs when one class is inherited from another

In overloading the arguments and the return type must differ

In overriding, the arguments and the return type must be the same

In overloading the function name is the same, But it behaves differently depending on the arguments passed to them

In overriding the function name is same, but Derived class function can perform different operations from the base class

 

0 Comments