Summary: In this tutorial, we will learn what virtual function and function overriding are in C++ and how can we override a function in C++.

Introduction to Function Overriding

When we redefine a base class’s function in the derived class with the same function signature but with a different implementation, it is called function overriding.

Example:

In this example, we have overriden the base class’s display method in the derived class.

Function overriding is an example of runtime polymorphism because the binding of the function call statement to the matching function happens during the runtime of the program

Note: We cannot override a derived class method in the base class because it is the opposite of the inheritance.

What is a Virtual Function?

In C++, only redefining a base class’s method in the derived class is not enough.

Consider the following example for the instance:

Output:

virtual function in C++

In this program, although we have redefined the display function in the derived class, the version of the base class of the display function is still being invoked.

This is because we have not declared the display function of the base class as a virtual function.

By defining a function as virtual, it is ensured that the derived class version will be used if the same version of the function exists in the derived class, regardless of the reference (or pointer) type used for the function call.

In short, we should declare a function as virtual in the base class if we intend to override it in the derived class.

Syntax for the Virtual Function:

Example:

C++ Example: Function Overriding and Virtual Function

If we rewrite the previous program by defining the display function of the base class as virtual, we get the appropriate output.

Output:

virtual function example

This time we have successfully overridden the base class’s display() function using the virtual keyword.

Conclusion

Function overriding in C++ is a runtime polymorphism, where we redefine a base class’s method in the derived class.

When working with reference or pointer objects, we should declare a function as virtual in the base class, if we intend to override it in the derived class.

Leave a Reply

13 − 5 =