Function Overriding in C++ Programming


Overriding in Inheritance is used when you use a already defined method from a super class in a sub class, but in a different way than how the method was originally designed in the super class. A child class inherits the data members and member functions of parent class, but when you want to override a functionality in the child class then you can use function overriding.

Function Overriding. When the base class and derived class have member functions with exactly the same name, same return-type, and same arguments list, then it is said to be function overriding.

This C++ program demonstrates Function Overriding using a base class base and a derived class derived.

  • The base class has a public function add() which accepts two integers as input and returns their sum. The derived class derived is derived from the base class base using the public access modifier. The derived class also has a public function add() that overrides the function add() of the base class.
  • When the program is executed, it first creates an object b of the base class and calls the function add() on it. The function add() of the base class asks the user to enter two integers and returns their sum.
  • Then, the program creates an object d of the derived class and calls the function add() on it. Since the function add() is overridden in the derived class, the program asks the user to enter three integers and returns their sum.
  • Finally, the program terminates by returning 0.

Source Code

#include<iostream>
using namespace std;
//Function Overriding in c++
class base
{
protected:
    int a,b;
public:
    void add()
    {
        cout<<"\nEnter 2 Nos : "<<endl;
        cin>>a>>b;
        cout<<"Total : "<<a+b<<endl;
    }
 
};
class derived:public base
{
private :
    int c;
public:
    void add()
    {
        cout<<"\nEnter 3 Nos : "<<endl;
        cin>>a>>b>>c;
        cout<<"Total : "<<a+b+c<<endl;
    }
};
int main()
{
    base b;
    b.add();
    derived d;
    d.add();
    return 0;
}
 
 

Output

Enter 2 Nos :
12
25
Total : 37

Enter 3 Nos :
67
4
34
Total : 105
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples