Function Overriding in C++
Updated on 06th Dec, 23 9.1K Views

In this blog, you will learn about function overriding in C++. This post will cover everything about function overriding in C++, from what it is and its working mechanisms to different ways to achieve this in our C++ programs. Moreover, you will also get to learn the difference between function overloading and function overriding.

Table of Contents:

Get started with learning C language. Check out our Youtube video on the C programming language for absolute beginners.

What is Function Overriding in C++?

Function overriding is the concept in C++ that allows us to redefine a function from the base class (parent class) to the derived class (child class). The function name and function signature (return type and parameters) remain the same in both classes. The function present in the derived class, is called the overriding method or function. The function in the base class is said to be overridden by the function of the derived class. This concept of function overriding in C++ comes under run-time polymorphism or late binding because the function call is decided at the run-time of the program rather than compile time. 

Function overriding helps enhance code readability. Even though both classes contain the same functions, the derived class function is independent of the base class. It allows different behaviors of a function in the derived class while using a common interface defined in the base class.

Syntax for Function Overriding

To implement function overriding in C++, the syntax is as follows:

//Syntax for Function Overriding in C++
public class parentClass {
  access_modifier:
    //overridden function 
    return_type functionName(){ }
  };
}
public class childClass : public parentClass {
  access_modifier:
    //overriding function
      return_type functionName(){ }
  };
}

Want to jumpstart your career in Computer programming? Enroll in our C Programming Course and gain skills to succeed!

Working of Function Overriding in C++

To achieve function overriding in C++, we first create a function inside the base class. A function consists of four parts, i.e., function name, function parameters, function definition, and function return type. These components are discussed in detail in the following section:

  • Function name: This is the identifier or name that we use to identify the function. This defines the purpose of the function, and while calling the function, this name is used.
  • Function parameters: Parameters are the information that will be passed to a function. There can be as many parameters in a function as you want. These are passed inside the brackets just after the name of the function. These act as variables inside the function.
  • Function definition: The function definition, or the body, contains the code that will be implemented. The code is the set of instructions for performing some operation.
  • Return Type: This specifies the type of value a function will return. For example, if a function returns an integer value, then it will have an int return type. On the other hand, if the function does not return anything, then the return type will be void.

After creating a function in the base class, we need to create a derived class by using the concept of inheritance. Inside the derived class, we will create the function with the same function name, parameters, and return type as the function in the base class. The function definition can be different for both functions.

Once we have created the function to be overridden (in the base class) and the function that will override (in the derived class), we will create an object of the derived class inside the main function and then call the overriding function using the object of the derived class. The code inside the overriding function will be executed. If we wish to implement the base class function, we can, but only if it’s not declared virtual. For this, we will need to create an object of the base class. We will understand this with the help of the example given in the next section. 

Get 100% Hike!

Master Most in Demand Skills Now !

Example

//Program to demonstrate function overriding in C++
#include <iostream>
using namespace std;
class parentClass {
   Public:
//Overriden function
    void display() {
        cout << "Display() function inside the Base class called." << endl;
return void();
    }
};
class childClass : public parentClass {
   public:
//Overriding function    
void display() {
        cout << "Display() function inside the Child class called." << endl;
return void();
    }
};
//Driver code 
int main() {
    childClass c1;
    c1.display();
//To call the parent class function or the overridden function
    parentClass p1;
    p1.display();
   return 0;
}

In this program, we have the display() function in the parent class as well as in the child class. In the main() function, we created the object of the child class “c1”, and through this object, we call the display() function. Now, the display() function inside the parent class is overridden by the one in the child class. This leads to the execution of the display() function present in the child class. Moreover, to execute the parent class function, we have created the parent class object “p1”. 

Display() function inside the Child class called.

Display() function inside the Base class called.

Check out these Frequently asked C++ pattern programs to gain advanced knowledge.

How to Access Overridden Functions in C++

We can access the overridden function in multiple ways.  One method for this has already been discussed in the previous section. In that method, we created the object of the parent class and accessed the overridden function through that object. Besides that, we can access the overridden method through the object of the derived class as well. However, it is not possible to access it directly. The following section contains information about how we can do it:

1. By accessing the base class function inside the derived class using scope resolution operator:

// C++ program to access the overridden function through the derived class object

#include <iostream>
using namespace std;
class baseClass {
public:
void Intellipaat_display()
{
cout << "Function inside the base class(overriden method)" << endl;
}
};
class derivedClass : public baseClass {
public:
void intellipaat_display()
{
cout << "Function inside the derived class(overriding method)" << endl;
// call of overridden function
baseClass::Intellipaat_display();
}
};
int main()
{
derivedClass d1;
d1.Intellipaat_display();
return 0;
}

Here we have used the scope resolution (::) operator to access the parent class Intellipaat_display() function inside the derived class. At the time of the function call, the method inside the derived class is executed. This method has access to the base class function; therefore, the base class function is also executed.

The output will be:

Function inside the derived class(overriding method)

Function inside the base class(overridden method)

2. Accessing through the object of the derived class through scope resolution operator:

#include <iostream>
using namespace std;
class baseClass
{
public:
    // overridden function
    void intellipaat_display()
    {
        cout << "Function inside the base class(overridden method)"<<endl;
    }
};
class derivedClass : public baseClass
{
public:
    // overriding function
    void  intellipaat_display()
    {
        cout << "Function inside the derived class(overriding method)";
    }
};
int main()
{
    // create the object of the derived class
    derivedClass d1, d2;
    // call the overriding function
    d1.intellipaat_display();
    // call the overridden function of the Base class
    d2.baseClass:: intellipaat_display();
    return 0;
}

Here we have accessed the base class function in the main class by using the scope resolution operator.

The output of this program will be:

Function inside the derived class(overriding method)

Function inside the base class(overridden method)

3. By using pointers:

#C++ code to demonstrate the access of overridden method by using pointers

#include <iostream>
using namespace std;
class baseClass
{
public:
   //overridden function
    void intellipaat_display()
    {
      cout << "This is the base class function"<<endl;
    }
};
class derivedClass : public baseClass
{
public:
    // overriding function
    void intellipaat_display()
    {
        cout << "This is the derived class function.";
        // call the overridden function of the base class
    }
};
int main()
{
    // creating object of the derived class
    derivedClass d1;
    // pointer of base class type
    baseClass *ptr = &d1;
    // call the overridden function
    ptr->intellipaat_display();
    return 0;
}

Here we are using the pointer “ptr” of the base class type, which stores the address of the object of the derived class. As the pointer is of base class type, it executes the base class function. This program gives the following output:

This is the base class function

Check out C++ interview questions with answers to ace your next C++ interview.

Career Transition

Non-Tech to IT Associate | Career Transformation | AWS Certification Course - Intellipaat Reviews
Non Tech to DevOps Engineer Career Transition | Intellipaat Devops Training Reviews - Nitin
Upskilled & Got Job as Analyst After a Career Break |  Data Science Course Story - Shehzin Mulla
Successful Career Change after Completion of AWS Course - Krishnamohan | Intellipaat Review
Got Job Promotion After Completing Artificial Intelligence Course - Intellipaat Review | Gaurav
Intellipaat Reviews | Big Data Analytics Course | Career Transformation to Big Data | Gayathri

Variation in Function Overriding (With Example)

There is a variation of method overriding, i.e., virtual function overriding, which means we can override the function by using the concept of a virtual function as well.

In this scenario, we use the keyword “virtual” inside the base class with the name of the function that we want to override. Here we use the pointer or reference to the base class that refers to the derived class object. We can call the virtual function through that object and execute the method present in the derived class. Consider the following example to understand the concept:

// C++ program to illustrate the concept of Virtual Function overriding

#include <iostream>
using namespace std;
class baseClass {
public:
virtual void print() { cout << "base class function\n"; }
};
class derivedClass: public baseClass {
public:
void print() { cout << "derived class function\n"; }
};
int main()
{
baseClass* ptr;
derivedClass d1;
ptr = &d1;
// Virtual function binding at run time
ptr->print();
return 0;
}

This code will give the following output:

derived class function

Difference Between Function Overloading and Function Overriding

Both function overriding and function overloading are methods to achieve polymorphism, but they are entirely different concepts. The following table highlights the main differences between the two concepts.

Function OverridingFunction Overloading
It falls under run-time polymorphism.It is a form of compile-time polymorphism.
Inheritance is required for overriding a function, which means we cannot achieve overriding within the same class.Function overloading does not require inheritance.
We cannot override a function multiple times at the same time as it is resolved at runtime.As it is resolved at compile time, we can overload a function multiple times at the same time.
We can have only one overriding function in one derived class.There can be any number of overloaded functions in a class.
Functions are of the same scope.Functions have different scopes here.
The function signature should be the same for the overriding and the overridden function.Functions should have different signatures.

Check the C++ project ideas to get ideas for your next project.

Conclusion

In C++ programs, don’t be afraid of utilizing overriding where applicable to reduce duplication and make codebases more organized and maintainable over time. Proper use of overriding is an essential characteristic of well-designed, extensible C++ applications. This feature is useful for customizing class behavior and improving code reuse. But before learning about overriding, prior knowledge of inheritance and polymorphism in C++ is necessary.

Got doubts in your mind? Get them resolved from Intellipaat’s community page.

Course Schedule

Name Date Details
Python Course 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 09 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 16 Mar 2024(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *

Speak to our course Advisor Now !

Subscribe to our newsletter

Signup for our weekly newsletter to get the latest news, updates and amazing offers delivered directly in your inbox.