The Fundamentals of Function Overriding in C++

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.

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.  

Syntax to Implement Function Overriding in C++

The following is the general syntax to implement function 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.

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

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

Advantages of Function Overriding

The concept of function 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.

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. 

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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

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!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.