Function Overriding in C++ [Function Overloading vs Overriding with Examples]
By Rohan Vats
Updated on May 13, 2025 | 17 min read | 95.7K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on May 13, 2025 | 17 min read | 95.7K+ views
Share:
Table of Contents
Did you know that C++ is ranked the second most popular programming language in the world in 2025, with a usage rating of 9.94%? This is mainly due to its powerful features, like Function Overriding in C++, which enable developers to create flexible and efficient object-oriented systems.
Function overriding in C++ refers to the ability of a derived class to provide its specific implementation of a function that is already defined in its base class. This allows polymorphism, where the correct function is called based on the object’s type at runtime. Function overloading, on the other hand, involves defining multiple functions with the same name but different parameters within the same scope.
In this blog, we will explore the key differences between function overloading and overriding, providing clear examples to illustrate how each works. By the end, you'll have a solid understanding of both concepts and their applications in C++.
Want to sharpen your C++ skills for web development? upGrad’s Online Software Development Courses can equip you with tools and strategies to stay ahead. Enroll today!
Function overloading in C++ is a feature of object-oriented programming. It allows multiple functions to share the same name within the same scope but differ in the number or type of parameters. This feature enables you to define different versions of a function that handle varying inputs without needing separate function names. When the program runs, the compiler selects the correct version based on the provided arguments. This process is known as compile-time polymorphism.
If you want to learn essential software development skills and function overriding in C++, the following courses can help you succeed.
Now, let’s explore some core aspects of function overriding in C++, such as parameter type variation.
1. Parameter Type Variation
Function overloading can be achieved by changing the data types of parameters. For instance, you can create two versions of the same function with different parameter types and allow a single function name to handle multiple data types.
cpp
void display(int number) {
cout << "Integer: " << number << endl;
}
void display(double number) {
cout << "Double: " << number << endl;
}
In this example, the display() function is overloaded. One version accepts an int, while the other accepts a double. This lets you use display() for both integer and floating-point numbers without creating two separate function names.
2. Parameter Count Variation
Another way to overload functions is by changing the number of parameters they accept. For example, you could design a function to perform a task differently based on whether it receives one, two, or more arguments.
cpp
int calculateArea(int side) {
return side * side; // Area of a square
}
int calculateArea(int length, int width) {
return length * width; // Area of a rectangle
}
Here, calculateArea() is overloaded. With one parameter, it calculates the area of a square. With two parameters, it computes the area of a rectangle. This flexibility makes the code more readable and easier to use.
Function overloading simplifies code by allowing multiple functions with the same name but different parameters. This flexibility helps avoid the clutter of multiple function names while maintaining clear, intuitive code. Now, let's explore the key benefits of using function overloading in C++.
If you want to gain expertise on C++ with AI and ML, check out upGrad’s Executive Diploma in Machine Learning and AI with IIIT-B. The program will help you gather expertise in NLP, GenAI that can streamline your software development process.
Here’s an example combining both parameter type and count variations for an add() function. Each version is suited to different input combinations:
cpp
// Adding two integers
int add(int a, int b) {
return a + b;
}
// Adding three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Adding two floating-point numbers
double add(double a, double b) {
return a + b;
}
</> Copy Code
In this setup:
When you call add(), the compiler will automatically choose the correct version. It does this by matching the argument types and counts with the appropriate function definition.
Function overriding in C++ allows a derived class to redefine a function inherited from its base class. It requires an exact match in the function name, parameters, and return type between the base and derived class functions. This feature is essential for runtime polymorphism, as it allows the program to dynamically determine which function to call based on the object type.
Function overriding provides flexibility by allowing derived classes to customize and deliver specialized behavior for an inherited function.
Consider a C++ application that models different types of vehicles. You have a base class Vehicle with a function StartEngine (). Now, you want each specific vehicle type to provide its own implementation of StartEngine () because the startup procedure differs between vehicles, like motorcycles.
By overriding the StartEngine () function in each derived class, you can ensure that each vehicle starts its engine according to specific needs. This function overriding in C++ allows for flexible, runtime polymorphism, where the correct StartEngine () function is called based on the actual object type.
Code Example:
|
Output:
|
Function Overriding in C++ is shown by the startEngine() method in the derived classes Car and Motorcycle, which overrides the base class Vehicle's method. The base class pointer vehiclePtr dynamically calls the overridden function based on the actual object type at runtime, demonstrating runtime polymorphism.
Now, let’s understand the key aspects of function overriding in C++.
Function overriding in C++ allows derived classes to redefine methods inherited from a base class, with or without polymorphic behavior. In basic overriding, the derived class simply replaces the base class function, but polymorphism is not achieved without the virtual keyword.
However, virtual functions enable dynamic binding, ensuring the correct function is called based on the actual object type at runtime. This allows for true polymorphism and more flexible object-oriented programming.
1. Basic Function Overriding in C++
In basic function overriding, the derived class redefines a method inherited from the base class without using any special keywords. This redefined function in the derived class replaces the base class’s function when accessed through a derived class object. However, without the virtual keyword, there’s no polymorphic behavior.
cpp
class Animal {
public:
void speak() {
cout << "Animal speaks." << endl;
}
};
class Dog : public Animal {
public:
void speak() { // Overrides speak() in Animal
cout << "Dog barks." << endl;
}
};
</> Copy Code
Here, speak() in the Dog class overrides speak() in Animal. If we create a Dog object and call speak(), the output will be "Dog barks." This demonstrates basic function overriding.
2. Virtual Function Overriding in C++
To achieve true polymorphism, we use virtual functions. Declaring a function as virtual in the base class allows the derived class to override it. When accessed through a base class pointer or reference, the program calls the overridden function in the derived class, enabling dynamic binding.
cpp
class Shape {
public:
virtual void draw() { // Virtual function in base class
cout << "Drawing shape." << endl;
}
};
class Circle : public Shape {
public:
void draw() override { // Overrides draw() in Shape
cout << "Drawing circle." << endl;
}
};
</> Copy Code
In this example, draw() in Shape is a virtual function, allowing Circle to override it. If we create a Shape pointer that points to a Circle object and call draw(), the Circle’s draw() function will execute, showcasing polymorphic behavior.
3. Non-Virtual Function Overriding in C++
Function overriding without virtual limits polymorphism. Overriding a non-virtual function in the derived class simply replaces the base class’s version, but only for derived class objects. This approach is uncommon in OOP as it lacks the flexibility of dynamic binding.
cpp
class Vehicle {
public:
void info() { // Non-virtual function
cout << "This is a vehicle." << endl;
}
};
class Car : public Vehicle {
public:
void info() { // Overrides info() in Vehicle
cout << "This is a car." << endl;
}
};
</> Copy Code
Here, info() in Vehicle is overridden in Car, but without the virtual keyword. Calling info() on a Vehicle pointer to a Car object would execute Vehicle’s info() rather than Car’s, showing no polymorphism.
Now, let’s understand the primary reasons for function overriding in C++.
Function overriding allows derived classes to modify inherited methods, enhancing flexibility and enabling more specialized functionality. It supports runtime polymorphism by enabling dynamic binding, which is essential for building extensible and scalable systems in languages like Python, C#, and R. Additionally, it promotes code reusability by allowing derived classes, promoting cleaner, more maintainable code across various platforms such as Apache Spark and ReactJS.
1.Enhanced Flexibility: Function overriding enables derived classes to modify inherited functionality, allowing them to be tailored for more specific tasks. This results in more adaptable and specialized courses, enhancing overall design flexibility in languages like Python, C#, and frameworks like ReactJS.
Example: In a banking application, a BankAccount base class could have an overridden calculateInterest() function in derived classes like SavingsAccount and CheckingAccount, each implementing different interest calculation methods.
2.Runtime Polymorphism: Virtual function overriding is key to runtime polymorphism, where the correct method is dynamically bound at runtime, depending on the actual object type. This is particularly useful in object-oriented languages like C++ and R and distributed systems like Apache Spark, enabling more efficient and extensible code.
Example: In a drawing application, a base class Shape could have an overridden draw() function, where each derived class (Circle, Rectangle) implements a different drawing method, selected at runtime based on the object type.
3.Code Reusability: Function overriding promotes code reusability by building upon and modifying base class functions. It reduces redundancy, encouraging classes to adapt rather than duplicate logic, making the codebase more maintainable across various languages and frameworks.
Example: A Vehicle class can define a general startEngine() method, while derived classes like Car and Truck can override it with their own specific implementations, reducing duplication and enhancing maintainability.
4.Improved Maintainability:
Overriding helps keep code modular and easier to maintain by enabling derived classes to change behavior without altering the base class.
Example: In a customer service application, a SupportTicket base class could define a resolveIssue() method, and each derived class (e.g., TechnicalTicket, BillingTicket) can override it without modifying the general ticket handling logic.
5.Better Modularity:
Function overriding enhances the modularity of code by allowing different classes to define their unique behaviors.
Example: In an e-commerce platform, a base class PaymentMethod could have an overridden processPayment() method, where each derived class (CreditCard, PayPal) handles the payment process differently, keeping the system flexible and easily extendable.
This example uses a base Animal class with a virtual function sound() and derived classes Dog and Cat, each with its own version of sound().
cpp
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Some generic animal sound." << endl;
}
};
class Dog : public Animal {
public:
void sound() override { // Overrides sound()
cout << "Woof Woof." << endl;
}
};
class Cat : public Animal {
public:
void sound() override { // Overrides sound()
cout << "Meow." << endl;
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->sound(); // Outputs: Woof Woof
animal2->sound(); // Outputs: Meow
delete animal1;
delete animal2;
return 0;
}
</> Copy Code
In this example:
If you want to learn more about function overriding in C++, check out upGrad’s Object Oriented Analysis and Design for Beginners. The 7-hour free program will enable you to gain expertise in procedural programming and more.
Let’s explore function overloading and function overriding in C++ with their differences.
Function overloading happens at compile-time and allows multiple functions with the same name but different parameters (varying by type or count) to exist in a class. This improves readability and makes it easy to use one function name to handle different types of inputs. Overloading doesn’t rely on inheritance, so it can be used within a single class.
Function overriding, in contrast, takes place at runtime and requires inheritance. It lets a derived class define its own version of a function that’s already in the base class, supporting polymorphism. This means the function used depends on the object’s actual type when called.
Here are some of the key differences between function overloading and function overriding.
Here’s a tabular format summarizing the difference between function overloading and function overriding in C++.
Summary Table
Feature |
Function Overloading in C++ |
Function Overriding in C++ |
Purpose | Enables multiple functions with the same name but different parameter types or counts. | Allows a derived class to modify or replace the base class method. |
Inheritance | Not necessary; it can occur within the same class or between unrelated classes. | Required, as it's done through inheritance from a base class. |
Timing | Resolved at compile-time (static binding). | Resolved at runtime (dynamic binding) using virtual functions. |
Function Signature | Varies by parameter types, count, or qualifiers. | Identical in both base and derived classes. |
Binding | Static binding (resolved during compile-time). | Dynamic binding (resolved during runtime using virtual mechanisms). |
Use Case | To perform the same operation with different input types or counts. | To modify or extend the behavior of a base class method in the derived class. |
Also read: Difference Between Overloading and Overriding in Java: Understanding the Key Concepts in 2025
Function overloading allows developers to define multiple functions with the same name but different parameters. This makes code more flexible and reusable, as it enables performing similar tasks on different data types or structures. Below, we'll explore practical examples of function overloading to calculate areas for different shapes.
This example demonstrates overloading the display() function to output different data types: an integer and a string. By overloading, we can use the same function name display() to print either an integer or a string, depending on the input parameter.
cpp
#include <iostream>
using namespace std;
// Function to display an integer
void display(int num) {
cout << "Integer: " << num << endl;
}
// Overloaded function to display a string
void display(string text) {
cout << "String: " << text << endl;
}
int main() {
display(25); // Calls the integer version of display
display("Hello!"); // Calls the string version of display
return 0;
}
</> Copy Code
makefile
Integer: 25
String: Hello!
</> Copy Code
This example shows the overloading of the multiply() function to perform multiplication on different data types: two integers, and a double with an integer.
cpp
#include <iostream>
using namespace std;
// Function to multiply two integers
int multiply(int a, int b) {
return a * b;
}
// Overloaded function to multiply a double and an integer
double multiply(double a, int b) {
return a * b;
}
int main() {
int intResult = multiply(4, 5); // Calls the integer version of multiply
double doubleResult = multiply(3.5, 2); // Calls the double version of multiply
cout << "Multiplication of integers: " << intResult << endl;
cout << "Multiplication of double and integer: " << doubleResult << endl;
return 0;
}
</> Copy Code
php
Multiplication of integers: 20
Multiplication of double and integer: 7
</> Copy Code
This example highlights how we can use the same function name, multiply(), to perform different operations based on input types, streamlining the code while keeping it versatile.
In function overriding in C++ with example, a child class changes the behavior of a function it inherits from a parent class. This lets the child class define its own version of the function while keeping the original function in the parent class. Let’s use an easy example to understand this.
Imagine the RBI (Reserve Bank of India) as a parent class. It sets up basic banking rules like loan_policy() and insurance_policy(). Now, banks like SBI and HDFC inherit from RBI, but each bank has its own loan policy. With function overriding, SBI and HDFC can each create their specific loan policy, even though they follow RBI’s main rules.
Here’s an example in C++ to show how RBI as the parent class has a loan_policy() function, which is then overridden by SBI and HDFC.
cpp
#include <iostream>
using namespace std;
// Parent class representing RBI
class RBI {
public:
// RBI's loan policy
virtual void loan_policy() {
cout << "RBI Loan Policy: Standard interest rate.\n";
}
};
// Child class representing SBI
class SBI : public RBI {
public:
// SBI's loan policy
void loan_policy() override {
cout << "SBI Loan Policy: Special rate for SBI customers.\n";
}
};
// Child class representing HDFC
class HDFC : public RBI {
public:
// HDFC's loan policy
void loan_policy() override {
cout << "HDFC Loan Policy: Premium rate for HDFC customers.\n";
}
};
int main() {
RBI* rbi_ptr;
SBI sbi;
HDFC hdfc;
// Using RBI pointer to access overridden functions
rbi_ptr = &sbi;
rbi_ptr->loan_policy(); // Calls SBI's loan_policy
rbi_ptr = &hdfc;
rbi_ptr->loan_policy(); // Calls HDFC's loan_policy
return 0;
}
</> Copy Code
rust
SBI Loan Policy: Special rate for SBI customers.
HDFC Loan Policy: Premium rate for HDFC customers.
</> Copy Code
Let’s consider the Constitution as the parent class. Different countries take inspiration from other constitutions but customize them to fit their own needs. Here, we’ll create a base class Constitution with a general law_system() method. Then, USA_Constitution and UK_Constitution override this method with their specific systems.
cpp
#include <iostream>
using namespace std;
// Parent class representing general Constitution
class Constitution {
public:
virtual void law_system() {
cout << "General Law System: Basic legal framework.\n";
}
};
// Child class representing USA's legal system
class USA_Constitution : public Constitution {
public:
void law_system() override {
cout << "USA Legal System: Presidential system with checks and balances.\n";
}
};
// Child class representing UK’s legal system
class UK_Constitution : public Constitution {
public:
void law_system() override {
cout << "UK Legal System: Parliamentary system with monarchy.\n";
}
};
int main() {
Constitution* const_ptr;
USA_Constitution usa;
UK_Constitution uk;
const_ptr = &usa;
const_ptr->law_system(); // Calls USA's law_system
const_ptr = &uk;
const_ptr->law_system(); // Calls UK's law_system
return 0;
}
</> Copy Code
sql
USA Legal System: Presidential system with checks and balances.
UK Legal System: Parliamentary system with monarchy.
</> Copy Code
Let’s look at some common mistakes you can avoid in function overriding in C++.
When working with function overloading and overriding in C++, some mistakes are easy to make. Here’s a guide to avoid the most common ones, with examples for clarity.
1. Forgetting the virtual Keyword in the Base Class
Example:
cpp
class Base {
// Missing virtual keyword
void display() { std::cout << "Base class\n"; }
};
class Derived : public Base {
void display() { std::cout << "Derived class\n"; }
};
int main() {
Base* obj = new Derived();
obj->display(); // Outputs: "Base class" instead of "Derived class"
return 0;
}
</> Copy Code
Fix: Add virtual to the base class function to enable overriding.
2. Overloading with Identical Parameter Types
Example:
cpp
class Test {
void calculate(int x) { /*...*/ }
void calculate(int y) { /*...*/ } // Error: Same parameter type
};
</> Copy Code
Solution: Ensure each overloaded function has a unique signature by changing parameter types or the number of parameters.
3. Incorrect Use of Scope Resolution in Overriding in C++
Example:
cpp
class Animal {
public:
virtual void sound() { std::cout << "Some animal sound\n"; }
};
class Dog : public Animal {
public:
void sound() override { std::cout << "Bark\n"; }
};
int main() {
Dog dog;
dog.Animal::sound(); // Calls Animal's sound() instead of Dog's
return 0;
}
</> Copy Code
Tip: Use the scope resolution operator with the base class only if you want to explicitly call the base function.
Quick Reminders:
If you’re curious about coding or want to strengthen your programming skills, our C++ tutorials are designed just for you. These tutorials break down C++ in simple, clear steps, helping you learn at your own pace with real examples and practical exercises.
Start your C++ journey with upGrad’s tutorials—your first step into programming awaits!
Also read: Top 40 Open Source Projects in C++: From Beginner to Advanced
Function overloading allows for multiple functions with the same name but different parameters, enhancing code readability and reducing redundancy. It ensures dynamic polymorphism, enabling derived classes to provide specialized behavior. By utilizing these techniques effectively, developers can optimize their programs with compile-time and runtime flexibility. Moreover, it promotes cleaner, more maintainable, and extensible object-oriented designs in C++.
If you want to excel in C++, these are some of the additional courses that can help you understand C++ at its core.
Curious which courses can help you gain expertise in C++? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center.
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
References
408 articles published
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources