Function Overriding in C++ with Example

Function Overriding in C++ Programming Language is one of the important concept in C++.

Function Overloading is used to achieve run time polymorphism

What is Function Overriding in C++?

When two classes are in the inheritance hierarchy.

The parent class function is re-defined in the child class with the same method signature.

The re-defined function in the child class is known as overridden function and this process is called function overriding.   

Simple Example of Function Overriding in C++

Output

In the above program, class A & B both have a function (show()) with same name and same parameter list.

When we call a show() function of with the child class variable then child class show() is get called.

Why do we need function overriding?

Base or parent class is general in nature and child classes are specialize class.

Parent class function represents general behavior, to provide specific behavior according to child class we need to override function.

Function Overriding Example in C++

We have created a base class Shape. This class has one function draw().

This method prints Draw Shape.

But can you tell which shape it will draw?

Here Shape is not defined but we need draw() in all sub classes because subclasses are specific and it can draw specific Shape.

Class Triangle can draw Triange Shape

Class circle can Draw Circle Shape.

To implement child’s specific behavior by all subclasses we need to override a function.

Overriding provides new definition to an existing method.

How to Access Base Class overriden method using child object in C++

Function Overriding in C++
Fig: Inheritance Method Overriding

Here to call base class overridden method from Child class object Scope Resolution operator is used (::)

t.Shape::draw()

How to Access Base Class overriden method from child class in C++

Inside circles’s draw() we called Shape’s draw() function using scope resolution operator

Shape::draw()

Read More

Anonymous Object in C++

Virtual Function in C++

Abstract Class in C++

Categories C++