Function Overloading vs Overriding: An Easy Guide.

Welcome to an easy guide on Function Overloading and Function Overriding in C++! Have you ever wondered how to create different versions of the same function, or how to give a special power to a class that can change the behavior of its parent class? That’s where Function Overloading and Function Overriding come into play.

In this article, we’ll explore these powerful concepts in a simple way, understanding why they are essential, how they work, and how we can use them in our C++ programs. By the end, you’ll be equipped with the knowledge to customize functions and create flexible and dynamic code! Let’s dive in!

Function Overloading vs Overriding: An Easy Guide.
Function Overriding and Function Overloading in C++

What is Function Overriding in C++?

A function is like a set of instructions that does a certain job when you give it some information. When you make a new version of a function in a special kind of way in C++, it’s called “function overriding”. This means you make a new version of a function in a class that already had it, but you keep the same name, what it gives back, and what you give it. This is useful when you want different classes to do the same job in their own way. It’s part of a thing called “Runtime Polymorphism”.

Syntax:

C++
class Base {
  public:
    virtual void show() {
        // base class code
    }
};

class Derived : public Base {
  public:
    void show() {
        // derived class code
    }
};

What is Function Overloading in C++?

Function overloading in C++ refers to the ability to define multiple functions with the same name but different parameter lists within the same scope, typically within a class. This allows you to use the same function name for different operations, making the code more intuitive and readable. When you call an overloaded function, the compiler determines which version to use based on the number and types of arguments provided. This technique simplifies coding by letting you perform similar tasks with a single function name while accommodating various data types or argument combinations.

Syntax:

C++
return_type function_name(parameter_list1) {
    // Function body
}

return_type function_name(parameter_list2) {
    // Function body
}

// Additional overloaded functions can follow the same pattern

Why do we need Function Overriding and Function Overloading in C++?

In C++, both function overriding and function overloading serve the purpose of making our coding lives easier and more flexible.

Function Overloading: Imagine you need to perform similar actions but with different types of data or parameters. Instead of creating separate functions with different names, function overloading lets you use the same name for multiple functions, but each function performs slightly different tasks based on the input you provide. It simplifies code and makes it more readable.

Function Overriding: When you’re dealing with classes and inheritance, function overriding comes into play. It allows you to replace a function in a parent class with a new version in a child class. This is particularly useful when you want to customize a function’s behavior for specific instances while still maintaining a common interface. It’s like using a blueprint to build various houses with unique interiors.

How are Function Overriding and Function Overloading used in C++?

Function overriding in C++:

  • The method in the child class must share the same name, return type, and parameters as the one in the parent class.
  • When an object of the child class calls the overridden method, the modified behavior of the child class method is executed.
  • Function overriding enables customization of inherited methods, adapting them to suit specific needs in the child class.
  • It supports polymorphism, allowing objects of the child class to be treated as objects of the parent class, enhancing code flexibility and reusability.
  • Overall, function overriding is a crucial feature for refining and extending the capabilities of inherited methods in object-oriented programming.

Function Overloading in C++:

  • Function overloading allows multiple functions with the same name but different parameter lists.
  • Parameters can vary in number, type, or both.
  • The compiler differentiates functions based on parameter types and their order.
  • Enables writing concise, intuitive code by reusing function names for related tasks.
  • Increases code readability and maintainability.
  • Provides flexibility to perform similar operations on different data types without creating new function names.
  • Decided at compile-time which overloaded function to call based on arguments provided.
  • Example: Same function name “calculateArea” for calculating the area of a rectangle and circle by passing different arguments.
  • Enhances code organization and reduces redundancy.

Real-life Example

Function Overloading:

Imagine a scenario: You’re at a coffee shop, and there’s a menu that reads:

  1. Coffee()
  2. Coffee(string type)
  3. Coffee(string type, int size)

These are three ways you can order coffee. You can just ask for a generic coffee, specify the type (like “espresso” or “latte”), or even specify both the type and the size (like “large espresso”).

In C++ terms, this is like having multiple functions with the same name “Coffee” but different parameters. This is function overloading!

C++
void Coffee() {
    cout << "Serving a regular coffee" << endl;
}

void Coffee(string type) {
    cout << "Serving a " << type << " coffee" << endl;
}

void Coffee(string type, int size) {
    cout << "Serving a " << size << "ml " << type << " coffee" << endl;
}

Function Overriding:

Now, imagine there’s a special coffee shop for cold coffees. When you order a coffee here, it’s always served cold, irrespective of the original definition of a coffee. So, when you ask for a “latte”, you’ll get a “cold latte”.

In C++ terms, if there’s a base class ‘CoffeeShop‘ with a method Latte(), and a derived class ‘ColdCoffeeShop‘ that has its own version of the ‘Latte()‘ method, the derived class is said to “override” the base class’s method.

C++
class CoffeeShop {
public:
    void Latte() {
        cout << "Serving a regular latte" << endl;
    }
};

class ColdCoffeeShop : public CoffeeShop {
public:
    // Overriding the Latte function of the base class
    void Latte() {
        cout << "Serving a cold latte" << endl;
    }
};

If you create an object of ‘ColdCoffeeShop‘ and call it ‘Latte()‘ method, you’ll get a cold latte, not a regular one. This is function overriding!

Overview:

  • Function Overloading: Same function name, different parameters. Like ordering coffee in different ways at the same coffee shop.
  • Function Overriding: A derived class provides its own version of a method that’s already provided by its base class. Like a special cold coffee shop always serving cold versions of the usual coffees.

A Problem to Solve

Problem Statement:

You are building software for a library. The library provides books in two formats: physical and digital. You’re required to implement the following features using function overloading and function overriding:

  • Function Overloading: The library should be able to lend a book.
    • If no information is given, it simply lends a random physical book.
    • If the title is given, it lends a physical book with that title.
    • If the title and format (either “physical” or “digital”) are given, it lends the book in the specified format.
  • Function Overriding: The library has now introduced a new section for kids. The books in the kids’ section are always in physical format regardless of the requested format. If a book title from the kids’ section is requested, the system should always return it in physical format, overriding the general library’s behavior.

Guide:

  • Create a class named ‘Library‘ which has functions to lend books.
  • Use function overloading to implement different ways of lending books in the ‘Library‘ class.
  • Create a derived class named ‘KidsSection‘ that inherits from ‘Library‘.
  • Override the lending function in ‘KidsSection‘ to ensure that books are always lent in physical format.

Expected Functions:

In the ‘Library‘ class:

C++
void lendBook(); // Lend a random physical book
void lendBook(string title); // Lend a physical book with the given title
void lendBook(string title, string format); // Lend a book with the given title and format (either "physical" or "digital")

In the ‘KidsSection‘ class:

C++
void lendBook(string title, string format); // Always lend a physical book with the given title, irrespective of the requested format

Note: You don’t have to create a complete system with book inventory and other features. Just focus on the function overloading and overriding aspects.

Hint:

For overriding, remember that the function in the derived class must have the same name, return type, and parameters as the function in the base class.

Examples of Using Function Overriding and Function Overloading in C++

Let’s look at some examples to see how function overriding and function overloading can be used in C++. We’ll provide the code, the expected output, and a step-by-step explanation of how these features are used.

Example 1: Function Overriding

C++
#include<iostream>
using namespace std;

class Animal {
public:
    virtual void makeSound() {
        cout << "The animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "The dog barks" << endl;
    }
};

int main() {
    Dog d;
    d.makeSound();
    return 0;
}

Output:

C++
The dog barks

Explanation:

  • The Animal class is a base class that has a virtual function makeSound(). The implementation of this function outputs a generic sound message.
  • The Dog class is derived from the Animal class and overrides the makeSound() function. The implementation of this function outputs a specific message for a dog’s sound.
  • In the main function, an object of the Dog class is created.
  • The makeSound() function is called on the Dog object, which invokes the overridden function in the Dog class.
  • The output will be “The dog barks”, indicating that the makeSound() function in the Dog class is executed.

Example 2: Function Overloading

C++
#include<iostream>
using namespace std;

void print(int i) {
    cout << "Printing int: " << i << endl;
}

void print(double f) {
    cout << "Printing float: " << f << endl;
}

void print(char* c) {
    cout << "Printing character: " << c << endl;
}

int main() {
    print(5);
    print(500.263);
    print("Hello World");
    return 0;
}

Output:

C++
Printing int: 5
Printing float: 500.263
Printing character: Hello World

Explanation:

  • Three print functions are defined with different parameter types: int, double, and char*.
  • The first print function prints an integer.
  • The second print function prints a floating-point number.
  • The third print function prints a character string.
  • In the main function, different print functions are called with different arguments: an int, a double, and a character string.

Difference Between Function Overriding and Function Overloading

AspectFunction OverloadingFunction Overriding
DefinitionMultiple functions with the same name in the same scope, but different parameter lists.Reimplementation of a base class function in a derived class with the same name and parameters.
InheritanceNot dependent on inheritance hierarchy.Depends on inheritance hierarchy.
ParametersVary in type, number, or order.Parameters must match in type, number, and order.
Return TypeCan have the same or different return types.Must have the same return type.
ScopeWithin the same class or namespace.Between a base class and its derived class.
Virtual FunctionNot influenced by virtual functions.Often used with virtual functions.
Compile-Time DecisionDepends on the inheritance hierarchy.The compiler determines function based on the object’s type.
Base Function InvocationSame function name with different parameter types like int, and float.The base class function can be invoked using the derived class object.
Dynamic PolymorphismNot directly related to dynamic polymorphism.Linked to dynamic polymorphism.
ExampleBased on the function name and parameter list.Derived class redefines a base class function.
GoalProvides multiple functions for different use cases.Overrides base class behavior with new behavior.
SignatureDistinguished by parameter types and count.The base class function can be called using the scope resolution operator.
Difference Between Function Overriding and Function Overloading

The Pros and Cons of Using Function Overriding and Function Overloading

Function OverridingFunction Overloading
Pros1. Allows customization of behavior in subclasses.1. Enables a single function name for multiple tasks.
2. Supports dynamic polymorphism.2. Improves code readability and maintainability.
3. Facilitates runtime method selection.3. Provides a clear and logical organization of code.
Cons1. Can be complex and may lead to subtle errors.1. Can lead to confusion if overused or misused.
2. May introduce performance overhead.2. Requires careful parameter handling to avoid ambiguity.
3. Requires understanding of inheritance hierarchy.3. Can result in an excessive number of overloaded functions.
The Pros and Cons

Key Takeaways

Function Overriding and Overloading in C++:

  • Function Overriding lets a derived class redefine a base class function.
  • Helps implement polymorphism, allowing objects of different classes to be treated uniformly.
  • Dynamic binding enables the correct function to be called at runtime based on the object type.
  • Useful for implementing methods with similar names but different behaviors in subclasses.
  • Function Overloading enables multiple functions with the same name but different parameters.
  • Helps improve code readability and reusability by grouping related functions.
  • The compiler decides which overloaded function to call based on argument types and order.
  • Enhances code organization by avoiding the addition of function names.
  • Overall, these features empower programmers to create flexible and efficient programs.

Conclusion

In conclusion, function overriding and function overloading are fundamental parts of C++. They allow us to use the polymorphism feature in C++, which is a key aspect of object-oriented programming. So keep practicing, and soon you’ll be a pro at using function overriding and function overloading!

FAQs

  • What is function overriding in C++?
    • Function overriding in C++ is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by its parent class or superclass.
  • What is function overloading in C++?
    • Function overloading in C++ is a feature that allows us to have more than one function with the same name in the same scope. The functions must differ in the number or types of parameters.
  • Why do we use function overriding and function overloading in C++?
    • We use function overriding and function overloading in C++ to create more flexible and interactive programs. These features allow us to create different implementations of a function for different classes or to perform different actions depending on the number or types of parameters.
  • Can using function overriding and function overloading make code more confusing?
    • Yes, if you use function overriding and function overloading without a proper understanding, it can make your code more complex and harder to understand. It’s important to understand how these features work and when to use them.
  • What are some examples of using function overriding and function overloading in C++?
    • Some examples include creating different characters in a video game with unique abilities (function overriding), creating a simulation program for a zoo where different animals make different sounds (function overriding), and creating a calculator program that can add different numbers of parameters (function overloading).

For Learning More: https://en.cppreference.com/w/

Deepak Vishwakarma

Founder

RELATED Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.