View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Function Overriding in C++: What Sets It Apart from Overloading!

By Rohan Vats

Updated on Jul 09, 2025 | 17 min read | 95.89K+ views

Share:

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++ allows a subclass to redefine a method inherited from its base class, enabling runtime polymorphism. It works through virtual functions, where the overridden method in the derived class has the same signature as the base class. 

This mechanism ensures dynamic dispatch. It is widely used in real-world applications like GUI toolkits, game engines, and system-level libraries. This promotes flexibility and modular design.

This blog explores function overriding in C++, how it works with examples, key differences from overloading, when to use it, and its pros and cons.

Want to sharpen your C++ skills for web development? upGrad’s Online Software Development Courses, powered by top universities, offer an updated Generative AI curriculum and training in the latest tools and languages. Learn in-demand tech skills and get job-ready. Enroll now!

What is Function Overriding in C++?

Function overriding in C++ lets a derived class give its version of a function that it inherits from a base class. For overriding to work, the derived class function must have the same name, parameters, and return type as in the base class. 

This feature is key to runtime polymorphism. It allows C++ to decide at runtime which version of the function to run, based on the actual object. Overriding gives you the power to tailor inherited behavior, making your programs more flexible and dynamic.

If you want to learn essential software development skills and function overriding in C++, the following courses can help you succeed.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Key Technical Points:

  • Exact Match Required: When overriding, your function in the derived class must have the same name, parameters, and return type as in the base class.
  • Enables Runtime Polymorphism: You can decide which function runs at runtime based on the object type, not the pointer or reference type you're using.
  • Use of Virtual Functions: Always mark the base class function as virtual. This allows C++ to choose the correct function version when using base class pointers or references.
  • Driven by Dynamic Dispatch: The function call is resolved at runtime through a virtual table (vtable), letting you customize behavior in derived classes without touching the base.
  • Supports Better Design: Function overriding lets you adapt inherited functionality, following good OOP principles like the Open/Closed Principle, your base class stays unchanged, and you extend behavior as needed.
  • Efficient Memory Use: You can reuse the base implementation and override only what’s necessary, which helps optimize performance and keeps memory usage lean.

Use Case:

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:

#include <iostream>
using namespace std;

// Base class
class Vehicle {
public:
    // Virtual function
    virtual void startEngine() {
        cout << "Starting engine of Vehicle" << endl;
    }
};

// Derived class 1 - Car
class Car : public Vehicle {
public:
    // Overriding the base class function
    void startEngine() override {
        cout << "Starting engine of Car" << endl;
    }
};

// Derived class 2 - Motorcycle
class Motorcycle : public Vehicle {
public:
    // Overriding the base class function
    void startEngine() override {
        cout << "Starting engine of Motorcycle" << endl;
    }
};

int main() {
    // Creating base class pointer
    Vehicle* vehiclePtr;

    // Creating derived class objects
    Car myCar;
    Motorcycle myMotorcycle;

    // Base class pointer pointing to derived class objects
    vehiclePtr = &myCar;
    vehiclePtr->startEngine();  // Calls Car's startEngine()

    vehiclePtr = &myMotorcycle;
    vehiclePtr->startEngine();  // Calls Motorcycle's startEngine()

    return 0;
}

Code Explanation: 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.

Output:

Starting engine of Car
Starting engine of Motorcycle

Now, let’s understand the key aspects of function overriding in C++. 

Function Overriding in C++: Core Types Explained

Function overriding in C++ empowers developers to customize or extend base class behavior in derived classes. It is crucial for achieving polymorphism, which allows the correct method to execute based on the actual object at runtime. 

Let’s break down three core types: basic overriding, virtual function overriding (enabling dynamic binding), and non-virtual overriding (no polymorphism). Understanding how and when each approach works allows you to write more flexible, reusable, and maintainable object-oriented C++ code.

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.
Sample Code: 

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

Code Explanation: 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.

Output:

Dog barks

Also Read: Dynamic Binding in C++: Explanation and Implementation

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.
Sample Code: 

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

Code Explanation: 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.

Output: 

Drawing circle.

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.
Sample Code: 

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;

    }

};

Code Explanation: 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.

Output: 

This is a vehicle.

Now, let’s understand the primary reasons for function overriding in C++.

Why Use 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 PythonC#, 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.

Struggling to build modern, responsive web apps? upGrad’s React.js for Beginners course helps you master React step by step. Learn to create reusable components, dynamic UIs, and even build your Phone Directory app. 

Also Read: Top 19 C# Projects in 2025: For Beginners, Intermediate, and Advanced Level Professionals

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 (CircleRectangle) implements a different drawing method, selected at runtime based on the object type.

Feeling intimidated by coding? upGrad’s free online Python Programming course makes it easy. Master fundamentals with real-world examples, tackle hands-on exercises, and earn a certificate to grow your tech skills. Enroll now and start building your first Python projects today!

Also Read: Step-by-Step Guide to Learning Python for Data Science

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., TechnicalTicketBillingTicket) 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 (CreditCardPayPal) handles the payment process differently, keeping the system flexible and easily extendable.

Example Code Demonstrating Polymorphism through Virtual Function Overriding in C++:

Polymorphism in C++ allows the same function to behave differently depending on the object calling it. This is achieved through virtual function overriding, where a derived class provides its own implementation of a virtual function defined in the base class. Using base class pointers or references to call overridden functions, C++ ensures that the correct version is executed at runtime, not compile time.

This mechanism is essential for building flexible, extensible, and maintainable object-oriented code. In the example below, virtual function overriding demonstrates how different animals make distinct sounds, even when accessed through a common base class pointer.

Sample Code:

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

Code Explanation:

In this example:

  • The sound() function is virtual in Animal.
  • Dog and Cat classes override sound() with their implementations.
  • The program uses a base class pointer to call the correct function at runtime, demonstrating polymorphic behavior.

Output:
Woof Woof.
Meow.

Also Read: 30 Trending Ideas on C++ Projects For Students

Let’s explore function overloading and function overriding in C++ with their differences. 

Function Overloading vs. Function Overriding: Key Differences

Function overloading and overriding are core concepts in C++ that support polymorphism but work differently. Overloading allows multiple functions with the same name but different parameters within the same scope and is handled at compile time. Overriding lets a derived class redefine a base class method and is handled at runtime using virtual functions. Understanding their differences helps you write cleaner, more flexible, and object-oriented code.

Here are some of the key differences between function overloading and function overriding. 

  • Inheritance Requirement
    • Overloading: No inheritance is needed and can be done within one class.
    • Overriding: Requires inheritance, with the derived class function replacing the base class function.
  • Timing
    • Overloading: Happens at compile-time, with the compiler choosing the function based on parameter types and counts.
    • Overriding: Occurs at runtime, allowing the program to select the derived class function when accessed through a base class reference.
  • Function Signature
    • Overloading: Requires different signatures—either the number or type of parameters changes.
    • Overriding: Requires identical function signatures in the base and derived classes.
  • Binding and Scope
    • Overloading: Uses static binding, determined by the compiler.
    • Overriding: Uses dynamic binding, where the function called is based on the object’s type at runtime.
  • Purpose
    • Overloading: Provides options to perform similar tasks on different data.
    • Overriding: Allows the derived class to modify or add to the base class function.

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

Examples of Function Overloading in C++

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.

1. Function Overloading for display() Function

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.

Code Example

#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;
}

Code Explanation:

  • The display(int num) function is designed to print an integer value. When we pass an integer to display(), this version is called.
  • The display(string text) function is designed to print a string. When we pass a string to display(), this version is called.
  • This way, we only need to remember one function name, display(), which can handle different types of input based on the data type passed. The compiler automatically selects the correct version of display() based on whether we pass an integer or a string.

Output:
makefile
Integer: 25
String: Hello!

2. Function Overloading for multiply() Function

This example shows the overloading of the multiply() function to perform multiplication on different data types: two integers and a double with an integer.

Code Example:

#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;
}

Code Explanation:

  • multiply(int a, int b) is defined to take two integer values, multiply them, and return the result as an integer.
  • multiply(double a, int b) is defined to take a double and an integer, multiply them, and return the result as a double.
  • When multiply(4, 5) is called with two integers, it invokes the first function, which returns 20.
  • When multiply(3.5, 2) is called with a double and an integer, it invokes the second function, which returns 7.0.

Output:
Multiplication of integers: 20
Multiplication of double and integer: 7

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.

Function Overriding in C++ with example

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.

Think of RBI as a parent class with rules like loan_policy(). Banks like SBI and HDFC inherit these rules but override loan_policy() to set their own, while still following RBI’s framework.

1. RBI and Banks with Overriding Services

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.

Sample Code:

#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;
}

Code Explanation:

  • RBI sets a general loan policy.
  • SBI and HDFC each override this with their own loan policies.
  • Using an RBI pointer, we can access the specific loan policies of each bank, thanks to polymorphism.

Output:

SBI Loan Policy: Special rate for SBI customers.
HDFC Loan Policy: Premium rate for HDFC customers.

2. Overriding with an Analogy - Constitutions

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.

Sample Code:

#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;
}

Explanation

  • Constitution provides a general law_system().
  • USA_Constitution and UK_Constitution override this with their own systems.
  • The base pointer Constitution* lets us access the specific legal system for each country.

Output:

USA Legal System: Presidential system with checks and balances.
UK Legal System: Parliamentary system with monarchy.

Let’s look at some common mistakes you can avoid in function overriding in C++. 

Common Mistakes in Function Overloading and Overriding in C++

Function overloading and overriding in C++ can be tricky if not used correctly. Minor oversights like missing a virtual keyword or using slightly different parameter types can lead to bugs, unexpected behavior, or broken polymorphism. These mistakes often confuse the compiler or make your code harder to maintain. 

In this section, you'll learn the most common errors and how to avoid them with simple examples.

1. Forgetting the virtual Keyword in the Base Class

  • Problem: If the base class function isn’t marked as virtual, overriding won’t work as expected. The base class function will be called instead of the derived one, especially when using a base class pointer.

Example:

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;
}

Fix: Add virtual to the base class function to enable overriding.

2. Overloading with Identical Parameter Types

  • Problem: Attempting to overload functions with the same parameters doesn’t work. The compiler won’t know which function to call, resulting in a compilation error.

Example:

class Test {
    void calculate(int x) { /*...*/ }
    void calculate(int y) { /*...*/ } // Error: Same parameter type
};

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++

  • Problem: Using the scope resolution operator :: when calling a function directly on an object will call the base class function, not the overridden one. This can be confusing if you meant to use the derived class version.

Example:

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:

  • Add virtual to any base function you plan to override in a derived class.
  • Make sure overloaded functions have unique parameter signatures.
  • Avoid unnecessary scope resolution to prevent accidentally calling the base class function.

Also read: Top 40 Open Source Projects in C++: From Beginner to Advanced

How upGrad Can Power Your Learning Journey?

Function overriding in C++ lets derived classes redefine base class methods, enabling runtime polymorphism through virtual functions and dynamic dispatch. It is essential for writing clean, maintainable, and scalable object-oriented code. Strengthen your grasp by experimenting with small programs that override base methods. This hands-on practice builds confidence for real-world use.

Understanding function overriding and overloading takes consistent effort. upGrad supports your growth with expert guidance, real-world projects, and structured learning paths to make your C++ skills job-ready. 

Here are some additional courses to support your development journey:

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.

Reference:
https://www.tiobe.com/tiobe-index/

Frequently Asked Question (FAQs)

1. What is the role of the virtual keyword in function overriding in C++?

2. Can I override a non-virtual function in C++?

3. What happens if a base class function is not marked virtual?

4. How does dynamic binding work with function overriding in C++?

5. Can constructors and destructors be overridden in C++?

6. What is the significance of function signatures in function overriding?

7. What are some common mistakes to avoid when overriding functions in C++?

8. How does function overriding contribute to code extensibility in C++?

9. How does function overloading improve performance in C++ applications?

10. What are the benefits of using override in C++?

11. Can function overloading be used with template functions in C++?

Rohan Vats

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

+91

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

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks