Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconFunction Overriding in C++ Explained

Function Overriding in C++ Explained

Last updated:
8th Nov, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Function Overriding in C++ Explained

What Is A Function?

A function is a piece that belongs to a code for executing a stipulated task in a program. It is important to have first-hand knowledge about inheritance to learn function overriding inheritance implementation is a mandate to this function. A C++ function is a collection of statements clubbed together for executing a task. All programs have a main() function, and particular programs have added functions. The function declaration sends the function name, return type, and parameters to the compiler to determine the function body by the function definition. A function can be a procedure, a method, or a subroutine, and all C++ functions consist of a header and a body. 

Syntax of a C++ function:-

return_type function_name(parameter list) {

function body

}

Ads of upGrad blog

Components:-

  • Return Type- This denotes the function’s return value type.
  • Function Name- This represents the function’s name which makes up the function signature and the parameter list.
  • Parameters- This is a placeholder for the value that the function returns. When a function is called, the value passed to the parameter is known as the actual parameter.
  • Function Body- The function body comprises the list of statements defining the function’s task.

How to Call a Function

A function must be invoked or called before use, after which the control is transferred to it for performing the necessary task. The return statement gives back the control to the main program after this. The parameters and the function name must pass to call a function. Arguments can be passed to a function in multiple ways while calling it. The call types are as follows:-

  • Call by Value
  • Call by Reference
  • Call by Pointer

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Function Overriding in C++

The C++ override is an idea via which a function given the same name is defined. The base class function in overriding is redefined within the derived class, which overrides the base class function. Implementing the run-time polymorphism can also be defined as function overriding. Here, the run-time of the program overrides the function.  

Function overriding allows programmers to use a function in the child class found in its parent class. As a result, the child class inherits every data member and the member functions found in the parent class. For overriding any child class functionality, you must implement function overriding. Function overriding refers to making a new version of the parent class function within the child class. 

Syntax to Implement Function Overriding in C++

When the same function defined in both the based and the derived class is called using the object from the derived class, it executes the derived class function. This is function overriding in C++. 

Down below is the most used syntax for the implementation of the function overriding in C++:

// C++ program for demonstrating function overriding

#include <iostream>

using namespace std;

class Base {

   public:

void print() {

     cout << “Base Function” << endl;

}

};

class Derived : public Base {

   public:

void print() {

     cout << “Derived Function” << endl;

}

};

int main() {

Derived derived1;

derived1.print();

return 0;

}

Output

Derived Function

This redefines the base class function within the derived class. Hence, the return-type, function_parameters, and function_name must be the same for achieving function overriding.

Popular Courses & Articles on Software Engineering

How Function Overriding Works in C++

OOPs must allow derived classes to inherit the features of the parent class. Function overriding enables the programmers to override any functionality within a class in a specific derived class. This is especially useful when a child class needs its functionality variant. 

Down below is a simple example of function overriding in C++ for your better understanding:

#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();

}

Access Overridden Function in C++

The scope resolution operator is used for accessing the overridden function of the base class in C++. The overridden function can also be accessed by using a base class pointer to point to an object of the derived class and then call the function from the pointer.

// C++ program to access overridden function

// in main() using the scope resolution operator ::

#include <iostream>

using namespace std;

class Base {

   public:

void print() {

     cout << “Base Function” << endl;

}

};

class Derived : public Base {

   public:

void print() {

     cout << “Derived Function” << endl;

}

};

int main() {

Derived derived1, derived2;

derived1.print();

// access print() function of the Base class

derived2.Base::print();

return 0;

}

Output

Derived Function

Base Function

The statement in the syntax; derived2.Base::print(); gives access to the the print() function of the Base class.

Call Overridden Function From Derived Class

You can use inheritance to change the behavior of a function. However, sometimes, you don’t need to change or replace the base/parent class functionality. Instead, more functionality must be added.

Below is an example of using the call overridden function from a derived class.

// C++ program to call the overridden function

// from a member function of the derived class

#include <iostream>

using namespace std;

class Base {

   public:

void print() {

     cout << “Base Function” << endl;

}

};

class Derived : public Base {

   public:

void print() {

     cout << “Derived Function” << endl;

     // call overridden function

     Base::print();

}

};

int main() {

Derived derived1;

derived1.print();

return 0;

}

Output

Derived Function

Base Function

In this program, the overridden function has been called inside the Derived class.

class Derived : public Base {

   public:

void print() {

     cout << “Derived Function” << endl;

     Base::print();

}

};

The code Base::print();, calls the overridden function within the Derived class.

Function Overloading vs. Function Overriding

Ads of upGrad blog

You can achieve function overloading at a compile-time, usually done within the derived and base classes. It provides more than one function definition by altering the signature of each function, like the data type or the return type of parameters.

Function overriding, on the other hand, can be achieved at run-time. The base class in overriding is redefined in the derived class with the same parameters and the same return type. Let’s find out what other features make these two functions different. 

OverridingOverloading
InheritanceRequires class inheritanceDoes not require class inheritance
Function SignatureDiffers in signature either in the type or the number of parameters.Function signatures stay the same
Function ScopeFunctions differ in scopeOwns the same scope
Function BehaviorRequired when a derived class function performs differently or with added functionality than the base class function.Required when functions bearing the same name have different behaviors based on the given parameters.

Conclusion

Function overriding in C++ helps save memory space and maintain the readability and consistency of any code. It also helps in making code reusable easily. Needless to say, knowledge about function overriding is an important skill to possess if you see a future for yourself in programming. 

If you want to join a reliable and premium course to kickstart your career in this field, you can sign up for the upGrad’s Master of Science in Computer Science on upGrad. Some of the key highlights of this program are as follows:-

  • Learn MERN Stack, Microservices, JavaScript, etc.
  • Wholesome learning on Cloud Labs
  • Experiment with tools used on Netflix, LinkedIn, Facebook, etc.
  • Get skilled in 10+ programming tools and languages
  • 24/7 student support

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

1How function overriding happens?

The function C++ override happens via inheritance, i.e. when one class inherits another class. When the derived class and the base class possess member functions having the same return type, name, and arguments list, it is called function overriding.

2What is the difference between function overloading and function overriding in C++?

Function Overriding happens when functions possess the same prototype in the base and derived classes. Function Overloading is performed when more than one function with a similar name exists in one class.

3What are the features of function overloading in C++?

Function overloading in C++ is primarily used for improving code readability. Programmers use it so they don’t have to memorize numerous function names. Classes with multiple functions, different parameters, and the same name are called Overloaded.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6054
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas &#038; Topics
12657
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions &#038; Answers [For Freshers &#038; Experienced]
5668
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions &#038; Answers in US [2024]
5393
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas &#038; Topics For Beginners [US 2023]
10927
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5458
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5557
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5041
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5532
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon