Function Overriding Example in C++


This code defines two classes Parent and Child where Child is derived from Parent class publicly. The Parent class has a member function display() which prints "Display Parent". The Child class has a member function display() that redefines the display() function of Parent class and prints "Display Child".

In the main function, an object of Parent class is created named o. The display() function of Parent class is called using the o object which prints "Display Parent".

Then an object of Child class is created named c. The display() function of Child class is called using the c object which prints "Display Child". Here, the function display() of Child class overrides the display() function of Parent class.

Source Code

#include<iostream>
using namespace std;
class Parent
{
public:
    void display()
    {
        cout<<"Display Parent"<<endl;
    }
};
class Child:public Parent
{
public :
    void display()
    {
        cout<<"Display Child"<<endl;
    }
};
int main()
{
    Parent o;
    o.display();
    Child c;
    c.display();//Redefined Function Override
    return 0;
}
To download raw file Click Here

Output

Display Parent
Display Child


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