A function is a constituent piece of code that performs a specific task in a program. Now, to understand function overriding, you must understand inheritance first, as implementing inheritance is mandatory to override a function. Inheritance is one of more vital concepts of OOPs that allows a derived class to inherit the properties of its parent class. Function overriding provides you with a way to override an existing functionality of a class inside a particular derived class. This can be useful when a child class requires its own version of a functionality. 

Now, understand this with the help of an example. Consider a vehicle manufacturing company “Ford”. A “Car” manufactured by this company inherits properties like brand name and vehicle type i.e. “Four Wheeler” from it. However, the “Car” can have a more specific vehicle type like “Sports vehicle”. So, the vehicle type function of the class “Ford” can be overridden in the class “Car” having its own definition of the function.

What is Function Overriding in C++?

Function overriding in C++ is a concept by which you can define a function of the same name and the same function signature (parameters and their data types) in both the base class and derived class with a different function definition. It redefines a function of the base class inside the derived class, which overrides the base class function. Function overriding is an implementation of the run-time polymorphism. So, it overrides the function at the run-time of the program.  

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Syntax to Implement Function Overriding in C++

The following is the general syntax to implement method overriding in C++:

public class Base{

  access_modifier:

    // overridden function

    return_type function_name(){}

  };

}

  public class Derived : public Base {

    access_modifier:

      // overriding function

      return_type function_name(){}

    };

  }

It redefines the function of the base class in the derived class, so the return-type, function_name, and function_parameters should be the same to achieve function overriding.

How Does Function Overriding Work in C++?

To understand the working of function overriding in C++, consider a simple example:

#include <iostream>

using namespace std;

class parent_class

{

public:

    virtual void print()

    {

        cout << "\nThis is print() method"

                " of BaseClass";

    }

};

class derived_class : public parent_class

{

public:

    // Function Overriding - new definition of

    // print method of base class

    void print()

    {

        cout << "\nThis is print() method"

                " of the Derived Class";

    }

};

// Driver code

int main()

{

    derived_class obj;

    obj.print();

}

 Function_Overriding_In_Cpp_1

In the above example, it defines the print() function in both the base class, that is, parent_class as well as the derived class i.e., derived_class with the same function signature but a different function definition. So, when you access the print() function using the derived class object d_obj, the derived class function overrides the base class function (consider the below code snippet).

Function_Overriding_In_Cpp_2

Example of Function Overriding From Real-life

An example of function overriding can be seen in various types of vehicles. For instance, we have a base class called "Vehicle" that has a function called "drive", which simply prints out a message saying "Driving the vehicle". Now, let's say we have two derived classes, "Car" and "Motorcycle", which both inherit from the "Vehicle" class. Both "Car" and "Motorcycle" classes have their own implementation of the "drive" function that is more specific to their type. For example, the "Car" class may print out "Driving the car" while the "Motorcycle" class may print out "Riding the motorcycle". When we call the "drive" function on an object of the "Car" class or the "Motorcycle" class, the implementation in the derived class will be executed instead of the implementation in the base class.

Example 

Elements of Function Declaration in C++

Before we dive deeper into function overriding, let's take a quick look at the elements of a function declaration in C++:

General Syntax:

return_type function_name (parameters) {

    // Function body

}

  • Return Type: The return type of a task defines the type of value which that task returns. For instance, if a task returns an integer when the return type of that task would be "int".
  • Function Name: The function name is the identifier used to implement the function from the other parts of the code. The function name should be meaningful and can display the purpose of the function.
  • Parameters: A function's parameters are the inputs that can be used in the function body to do calculations or manipulate any data type with zero or more parameters.
  • Function Body: The function body is the code implemented when the function is started. It has the logic for the function.

Calling a Function: A function is called using its name followed by parentheses containing any necessary arguments. For example, to call a function named "myFunction" that takes two integers as arguments, the syntax would be "myFunction(5, 10)".

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Advantages of Function Overriding

The concept of method overriding in C++ serves various advantages. Some of the major advantages are as follows:

  1. Function overriding helps to improve the readability of the code.
  2. If both the child class and base class have the same function, it will not affect the independence of the child class function.

#include <iostream>

using namespace std;

//base class

class parent_class

{

public:

  //function to calculate area of a 2D shape

  virtual void area(int side1, int side2)

  {

    //function definition

    cout << "Area is: " << (side1 * side2) << endl;

  }

}; 

//derived class

class derived_class : public parent_class

{

public:

  // function to calculate area of a triangle

  void area(int side1, int side2)

  {

    //function definition

    cout << "Area is: " << (0.5 * side1 * side2) << endl;

  }

};

 int main()

{

  parent_class square, rectangle;

  derived_class triangle;

  // area() of base class is called

  square.area(2, 2);

  rectangle.area(4, 5);

  // area() of derived class is called

  triangle.area(4, 5);

  return 0;

}

 Function_Overriding_In_Cpp_3

In the example above, the derived class had its own implementation of the area() function. When an object of the derived class calls the area() function, the overriding function is called, which calculates the area of a triangle.

  1. Overriding a function saves the memory, increases the consistency of code, and enhances code reusability.
  2. A function with the same name can be used to perform different operations and hence makes the code clean. 

Examples of Function Overriding in C++

The following examples illustrate different scenarios to access the overridden function and the overriding function.

Example 1: Accessing Overriding Function

This example illustrates how to access the overriding function (that is the re-defined function inside the derived class).

#include <iostream>

using namespace std;

// define the base class

class parent_class

{

public:

    // define overridden function

    void display_message()

    {

        cout << "I am the base class function.\n";

    }

};

// define the derived class

class derived_class : public parent_class

{

public:

    // define overriding function

    void display_message()

    {

        cout << "I am the derived class function.\n";

    }

}; 

int main()

{

    // create object of derived class

    derived_class obj;

    // call the overriding function

    obj.display_message();

    return 0;

}

Function_Overriding_In_Cpp_4

In the above example, it redefines the function display_message() of the base class in the derived class. The return type and the function signature are the same in both classes. The display_message() function of the base class overrides the display_message() function  of the base class. So, when the derived class object makes a call to the display_message() function, it accesses the display_message() of the derived class.

Example 2: Accessing Overridden Function

As you have seen in the previous example, the object of the derived class accesses the overriding function (defined inside the derived class). However, you can also access the overridden function (defined inside the base class) by an instance of the derived class. 

The following example illustrates how to access the overridden function of the base class using the instance of the derived class.

#include <iostream>

using namespace std;

// define the base class

class parent_class

{

public:

    // define overridden function

    void display_message()

    {

        cout << "I am the base class function.\n\n";

    }

};

// define the derived class

class derived_class : public parent_class

{

public:

    // define overriding function

    void display_message()

    {

        cout << "I am the derived class function.\n\n";

    }

};

int main()

{

    // create instances of the derived class

    derived_class obj1, obj2;

    // call the overriding function

    obj1.display_message();

    // call the overridden function of the Base class

    obj2.parent_class::display_message();

    return 0;

}

Function_Overriding_In_Cpp_5.

In the above example, the scope resolution operator (::) is used to access the overridden function, display_message() of the base class. The statement obj2.parent_class::display_message() calls the display_message() function defined inside the base class.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Example 3: Accessing Overridden Function Inside the Derived Class

The overridden function of the base class can also be accessed by the derived class using the scope resolution operator (::). In this way, you can also access the overridden function by the instance of the derived class.

The following example illustrates how to access the overridden function of the base class inside the derived class.

#include <iostream>

using namespace std;

// define the base class

class parent_class

{

public:

    // define overridden function

    void display_message()

    {

        cout << "I am the base class function.\n\n";

    }

};

// define the derived class

class derived_class : public parent_class

{

public:

    // define overriding function

    void display_message()

    {

        cout << "I am the derived class function.\n\n";

        // call the overridden function of the base class

        parent_class::display_message();

    }

};

int main()

{

    // create instances of the derived class

    derived_class obj1, obj2;

    // both the overridden and the

    // overriding function will be accessed here

    obj1.display_message();

    return 0;

}

Function_Overriding_In_Cpp_6.

In the above example, the display_message() function of the base class is called inside the display_message() of the derived class using the scope resolution operator. This allows the instance of the derived class to access the overridden function of the base class indirectly.

Example 4: Accessing the Overridden Function Using a Pointer

You can also access the overridden function of the base class using a pointer of the base class type pointing to the object of the derived class. 

The following example illustrates how to access the overridden function of the base class using a pointer of the base class type.

#include <iostream>

using namespace std;

// define the base class

class parent_class

{

public:

    // define overridden function

    void display_message()

    {

        cout << "I am the base class function.\n\n";

    }

};

// define the derived class

class derived_class : public parent_class

{

public:

    // define overriding function

    void display_message()

    {

        cout << "I am the derived class function.\n\n";

        // call the overridden function of the base class

    }

};

int main()

{

    // create instances of the derived class

    derived_class obj;

    // pointer of base class type

    parent_class *ptr = &obj;

    // call the overridden function

    ptr->display_message();

    return 0;

}

Function_Overriding_In_Cpp_7

In the above example, it creates a pointer of the base class type. The statement parent_class *ptr = &obj creates a pointer ptr, which points to the object of the derived class. Even though the pointer is pointing to the derived class object, when the display_message() function is called, it executes the overridden function of the base class. This is because the pointer is of the base class type. 

Variations in Function Overriding (With Examples)

Function overriding offers greater flexibility and customization in programming. Let’s discuss the variations of method overriding in C++ with examples.

Basic Function Overriding

The most basic function overriding involves redefining a method with the same name and signature in a subclass. For example:

Example

class Animal {

public:

    virtual void speak() {

        std::cout << "Animal speaks!" << std::endl;

    }

};

class Dog : public Animal {

public:

    void speak() override {

        std::cout << "Dog barks!" << std::endl;

    }

};

int main() {

    Animal* animal = new Dog();

    animal->speak(); // prints "Dog barks!"

    delete animal;

    return 0;

}

In this example, the superclass Animal has a method speak(), and a subclass Dog that overrides this method with its implementation. When we create an instance of Dog and call its speak() method through a pointer to the Animal base class, we get the behavior we expect: for the dog to bark.

Virtual Function Overriding

In virtual function overriding, a function in the base class is declared with the word "virtual," indicating that a subclass may override it. When the function is called via a pointer or reference to the base class, the function's implementation in the required subclass is called.

Example:

class Shape {

   public:

      virtual void draw() {

         cout << "Drawing Shape" << endl;

      }

};

class Circle: public Shape {

   public:

      void draw() {

         cout << "Drawing Circle" << endl;

      }

};

int main() {

   Shape *shape;

   Circle circle;

   shape = &circle;

   shape->draw();

   return 0;

}

In this example, the Shape class has a virtual function called draw(), which is overridden by the Circle class. When the draw() function is called through a pointer to the Shape class, the function's implementation in the Circle class is called, resulting in "Drawing Circle" being printed to the console.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Non-Virtual Function Overriding

In non-virtual function overriding, a subclass implements a non-virtual function in the base class. This variation is less common than virtual function overriding because it is less flexible and cannot be used for polymorphism.

Example:

class Shape {

   public:

      void draw() {

         cout << "Drawing Shape" << endl;

      }

};

class Circle: public Shape {

   public:

      void draw() {

         cout << "Drawing Circle" << endl;

      }

};

int main() {

   Shape *shape;

   Circle circle;

   shape = &circle;

   shape->draw();

   return 0;

}

Function Overloading vs. Function Overriding

Although both function overloading and function overriding provide a way to achieve polymorphism, they differ in terms of several aspects including their definition,  implementation, and usage.

Function Overloading

Function overloading occurs when two or more functions have the same name along with the same return type but with different parameters.

Example

#include <iostream>

using namespace std;

class function_overload

{

public:

    // findArea() function with one integer parameter

    void findArea(int side1)

    {

        cout << "The area is: ";

        cout << (side1 * side1) << "\n\n";

    }

    // findArea() function with two integer parameters

    void findArea(int side1, int side2)

    {

        cout << "The area is: ";

        cout << (side1 * side2) << "\n\n";

    }

}; 

int main()

{

    function_overload obj;

    // call first findArea() function

    obj.findArea(5);

    // call second findArea() function

    obj.findArea(5, 6);

    return 0;

}

Function_Overriding_In_Cpp_8.

In the above example, the findArea() function is the overloaded function. When the function is called, the compiler matches the arguments with the function signature and it executes the matched function. So, the statement findArea(5) corresponds to the findArea() function with one integer parameter, and the statement findArea(5, 6) corresponds to the findArea() function having two integer parameters.

Function Overriding

When it redefines a function of the base class in a derived class with the same signature i.e., name, return type, and parameter but with a different definition, it is called function overriding.

Example

#include <iostream>

using namespace std;

class function_override

{

public:

    // findArea() function of the base class

    // it is the overridden function

    void findArea(int side)

    {

        cout << "The area is: ";

        cout << (side * side) << "\n\n";

    }

};

class derived_class : public function_override

{

public:

    // findArea() function of the derived class

    // it is the overriding function

    void findArea(int side)

    {

        cout << "The area is: ";

        cout << (0.5 * side * side) << "\n\n";

    }

}; 

int main()

{

    derived_class obj; 

    // overriding function is called

    obj.findArea(5); // 0.5 * 5* 5 is printed 

    return 0;

}

 Function_Overriding_In_Cpp_9

In the example above, it overrides the findArea() function of the base class by the findArea() of the derived class. When you make a call to this function by the object of the derived class, the overriding function is executed.

The following comparison chart highlights the key differences between function overloading and function overriding in C++:

Function Overloading

Function Overriding

Function overloading in C++ can occur with or without inheritance.

Function overriding in C++ can only occur in the presence of inheritance.

Overloaded functions must have different function signatures i.e., the number of parameters or the data type of parameters should be different.

Overridden functions must have the same function signature i.e., the number of parameters as well as their data type must be he same.

It represents the compile-time polymorphism or early binding as overloading occurs during compile time.

It represents the run-time polymorphism or late binding as overriding occurs during run time.

Overloading takes place within the same class

Overriding occurs in a parent class and its child class.

No special keyword is used to overload a function.

Virtual keyword in the base class and Override keyword in the derived class can be used to override a function.

Overloading is done to acquire the different behavior to the same function depending on the arguments passed to the functions. 

Overriding is done when the derived class function is expected to perform differently than the base class function. 

A class can have any number of overloaded functions.

There can only be one overridden function per derived class.

Execution of function is fast.

The function execution is comparatively slow.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Final Thoughts!

In this article, you learned an important object-oriented programming concept called method or function overriding in C++. You saw how to declare and define a function in the base class in C++ and then override it in the child class to carry out a different functionality. 

You learned important key concepts such as keeping the method signature intact while overriding a function, the working of function overriding, the syntax of implementing function overriding in C++, etc. Next, you saw several examples and use-case scenarios of function overriding in C++. Finally, you understood the fundamental differences between function overloading and overriding in C++.

If you want to learn more about other important and key concepts in C++, you can check out Simplilearn’s guide on C++ for beginners

Moreover, if you are looking for a prosperous career in Full Stack Web Development, you should definitely check out our 9-month comprehensive training program on Full Stack Web Development. This training is carried out by industry professionals and will help you to learn trending skills such as Java and its frameworks such as Spring, JPA, Hibernate, etc., DevOps, Agile, HTML, CSS, and many more. Moreover, you will have access to a capstone project at the end of the course to brush up on your skills.

If you are interested in learning various other skills as well, you can check out Simplilearn’s complete list of free online courses.

If you have any queries related to this article on “Function Overriding in C++” or any other suggestions, feel free to drop a comment and our experts will get back to you as soon as possible.

Happy Learning!