Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Function Overloading in C++

Back to home
Logicmojo - Updated Jan 19, 2023



Introduction

In C++, function overloading refers to the concept of allowing two or more functions to have different logic yet share the same function name. Overloading functions with distinct return types and identical parameters is not possible.

Overloading Types in C++ are:


If two functions with the same name are declared, what will happen? Will this result in an error?
Yes, provided that the parameters and their respective orders are same. In the absence of such, function overloading results. When many functions have the same name but different signatures, this is known as function overloading. The function call in this scenario determines which overloaded function to execute.

In C++, this issue is tackled in a different way. To cut down on the time it takes to call short functions, C++ adds a new function called the inline function.
This article will give the reader an overview of inline functions in C++, a crucial area of programming, and then show them in action.

The idea of object-oriented programming is present in C++ (also known as OOPS). We will talk about function overloading, one of the various OOPS features. Every programming language offers the option of using functions to reuse previously written code. The number and type of parameters provided to a function are typically determined by the definition of the function by the programmer. Function overloading is a feature of additional functions in programming languages that support OOPS ideas. It alludes to the possibility of having many functions with the same name but various argument values.

What is Function Overloading in C++

Function overloading is the term used in C++ to describe when two or more functions share the same name but have distinct parameters. The C++ function overloading feature is used to make the code easier to read. The programmer can avoid needing to memorise many function names thanks to it. Functions that are overloaded are those that are members of a class and have many instances with the same name but different parameters. If a particular operation needs to be done with a variety of numbers or kinds of parameters, the function must be overloaded.

The data type and order of the parameters are what I mean when I say "parameter list." For instance, the function myfunction's (int, double) argument list differs from the function's (double a, int b) parameter list in several ways (double, int). A polymorphism created at compile time is function overloading. Let's look at the overloading rules since we already understand what a parameter list is: we can have the following functions in the same scope.

sum(int a, int b)
sum(int a, int b, int c)

To further understand function overloading in C++, let's look at some samples.
By defining a function with a varying number of parameters, function overloading in C++ can be accomplished.

#include<iostream>  
using namespace std;  

// function with one argument
void display_func(int a) {
  cout << "a = "<<a<<endl;
}

// function with two argument
void display_func(int a, int b) {
  cout << "a = "<<a<<" and b = "<<b<<endl;
}

int main() {
  display_func(5);
  display_func(5,10);
  return 0;
}


What Effects Does Function Overload Have?

Overloading of functions must have:

      ⮞ More than one function definition uses the same function name.

      ⮞ Different parameters must be used with overloaded functions. This distinction can be made in function definitions by utilising a varied number of function parameters or parameters with various data types.

Following these two, the compiler can use a best match approach to distinguish uniquely which function needs to be called at compile time.
Because variables may hold the value of a specific data type, C++ is a statically typed programming language (int, char, bool, etc.)

For instance, a variable of type char can only hold characters and not integers, whereas a variable of type int can only store integer values. A type check is enforced in function arguments each time a function call is made to make sure the provided parameters and the data type of the function argument match its description. Choosing which function to call is decided upon at build time. Thus, the compiler can distinguish between two or more functions that have the same name but distinct parameters, enabling us to leverage the idea of function overloading in our applications.

Function overloading types in C++

In C++, there are two kinds of function overloading.
Overloading at compile time: Different signatures are used to overload functions during compile time overloading. A function's return type, parameter count, and parameter type are all part of its signature.
Runtime overloading - Runtime overloading involves using a varying amount of parameters to overload functions.

Function Overloading Causes

The compiler throws us an error because the call to the overloaded function is confusing when functions are improperly overloaded since it is possible for two or more overloaded functions to satisfy the restrictions given in the function call. Let's talk about a few of these typical compilation issues that result from improper function overloading.


Type conversion

When a floating number's data type is not specified in C++, type double is used to represent it instead of type float. Whenever floating numbers are supplied directly in a function call, we must make sure that the variables' data types are of type double, otherwise the compiler will throw an error.

#include<iostream>
using namespace std;

// Returns the absolute value of a float variable.
float absolute_find(float a){
    if (a < 0.0)
        a = -a;
    return a;
}

// Returns the absolute value of an integer variable.
int absolute_find(int a) {
     if (a < 0)
         a = -a;
    return a;
}

int main() {
    int a = absolute_find(-5);
    float b = absolute_find(3.4);
    
    cout<<"a = "<<a<<endl;
    cout<<"b = "<<b<<endl;
    return 0;
}


The code should produce the desired output if abs(-5) called the second method and abs(3.4) called the first function; however, it produces an error stating that the call to overloaded abs(double) is unclear.
Because C++ treats floating-point constants as being of type double rather than float, we encounter an error. Thus, changing the parameter type to double will result in the programme running as intended. This issue is classified as a conversion error from float to double.

Default arguments for a function

When no value is supplied to the function parameter in the function call, C++ permits function arguments to store a default value, which is assigned to the argument. We used to pay particular effort to avoid situations where functions that have default values for their parameters are overloaded because they frequently result in compilation errors.

#include<iostream>
using namespace std;
void function(int);
void function(int,int);

void function(int x)
{
    std::cout << "Value of x is : " <<x<< std::endl;
}
void function(int y,int z=12)
{
    std::cout << "Value of y is : " <<y<< std::endl;
    std::cout << "Value of z is : " <<z<< std::endl;
}
int main()
{
    function(12);
    return 0;
}


Because function(int y, int z=12) can be called in two different ways, the error message "call of overloaded 'fun(int)' is unclear" is displayed in the example above. By invoking the function with a single argument (which causes it to take the value of z = 12 by default) by using just two arguments when calling the function.

Function with a Pass by Reference

A function call can be made either by value or by reference. Call by reference refers to calls when parameters are supplied to a function by reference. We should be extremely cautious when trying to overload routines that have parameters given by reference because the call to an overloaded function is frequently unclear. In such situations, the compiler is unable to distinguish between them and produces an error. In the example below, one such instance is presented:

#include <iostream>
using namespace std;
void demo_func(int);
void demo_func(int &);
void demo_func(int a)
{
    std::cout << "Value of a is : " <<a<< std::endl;
}
void demo_func(int &b)
{
    std::cout << "Value of b is : " <<b<< std::endl;
}

int main()
{
    int x=10;
    demo_func(x);
    return 0;
}




Learn More

The C++ Function Overloading Rules

It is necessary for each function's parameters to be distinct in order for overloading to work properly. The three methods outlined above can be used to produce this uniqueness in function arguments.
There are various types of parameters for functions.

Different data types are permitted as parameters for every function. For instance:

int add(int a) {}
int add(double a) {}

Numerous different parameters
Functions can differ in the number of parameters they use to be distinguished by the compiler, such as

int sub(int a, int b) {}
int sub(int a, int b, int c) {}

There are several combinations of arguments for functions.
If two or more functions share the same arguments but in different configurations, for instance:

int add(int a, float b) {}
int add(float a, int b) {}

Benefits of C++ Function Overloading

      ⮞ The application is incredibly easy to use and comprehend.

      ⮞ It reduces memory usage, preserves consistency, creates a clear interface for methods independent of the kind of parameter, and improves programme readability.

      ⮞ The idea of function overloading allows us to create many functions with the same name, but the arguments they receive must be of distinct types.

      ⮞ Overloading functions speeds up programme execution.

      ⮞ Function overloading is employed to conserve memory and promote code reuse.

Drawbacks Function overloading in C++

      ⮞ The function overloading procedure cannot be used to overload function declarations that differ in their return type.

      ⮞ The same parameters or name types cannot be overloaded if a static member function is declared.

Function overloading and ambiguity

The overloading feature of the C++ programming language allows for the overloading of two or more methods with the same name but different parameters to produce compile-time polymorphism. It can be done using function and operator overloading. Function overloading involves using two or more functions with the same name but different parameters, as opposed to operator overloading, which uses extra operators to offer user-defined data types with specific meaning.

This feature allows using built-in operators on user-defined types. Operator overloading redefines functionality to fit user expectations, making the code simpler to understand. The application of function overloading and operator overloading in C++ will be covered in detail in this article.

The Overloading concept in C++ makes it possible to write adaptable and clear code. It reduces the requirement for duplicate code by allowing additional functionality to be added to the existing code with the fewest changes possible. Practically speaking, overloading is permitted in C++ in two different ways.

A C++ feature called function overloading enables us to write functions with the same name but different datatypes or amounts of arguments. This feature allows developers to define functions with the same name within the same scope. Compile-time polymorphism is made possible by the named functions having the same behaviour. Function overloading has the advantage of making the code simpler to read.

Function Overloading Vs Operator Overloading

Function OverloadingOperator Overloading
We can use function overloading to invoke it in many ways.Operator overloading enables operators to have meanings that go beyond their purely operational definitions.
The function with the same name and different parameters can be overloaded.In order to specify custom behaviour, you can overload operators like "+," "-," "()," and "[]."
Using a single name and adding more functionality to it is known as function overloading.Operator overloading refers to giving a certain operator more capability.
When an operator is overloaded, its meaning changes depending on the kind of its operands.When a function is overloaded, its signature, which is the list of argument types in the function's parameter list, might have distinct meanings depending on the context.


In C++, is it possible to overload the main() function?
In C++, the main() method can indeed be overloaded. We must use a class and declare the main() function as a member function in order to overload the main() function.

#include <iostream>
using namespace std;

class main_demo {
public:
    int main_demo(int a) {
         cout<<"a = "<<a<<endl;
        return 0;
    }

    int main_demo(int a ,int b) {
        cout<<"a = "<<a<<"; b = "<<b<<endl;
        return 0;
    }
};

int main_demo() {
    main_demo object;
    object.main_demo(5);
    object.main_demo(5,10);
    return 0;
}


Function Overloading Vs Function Overriding

Function OverloadingFunction Overridding
When two or more methods in a class have distinct parameters but the same method name, this is known as function overloading.One method is in the parent class and the other is in the child class when a function is overridden, but they have the same parameters and method name.
There should be a difference in the number or kind of parameters.The function signature should not change.
defines several methods' behaviours.alters the way the procedure behaves.
code improvement methodCode-replacement methodology
Compile Time PolymorphismRun Time Polymorphism


FAQs

What kinds of overloading are there?
Function overloading and operator overloading are the two different types of overloading.

What is Operator overloading?

It is a type of compile-time polymorphism used to redefine the operator and give it a unique definition for a certain data type.

What is the bare minimum of functions needed in C++ for function overloading?

Function overloading in C++ requires at least two functions with the same name but differing argument signatures.

How does function overriding work?

Function overriding is the process of having a function with the same name and parameters in both the parent class and the child class.

It is a compile-time polymorphism since the suitable function is chosen at compile-time.

How may function overloading be accomplished in C++?

In C++, function overloading is accomplished by declaring many functions with the same name but various numbers and kinds of parameters.

Conclusions

This concludes our discussion of "Function Overloading in C++." I sincerely hope that you learned something from it and that it improved your knowledge. You can consult the C++ Tutorial if you want to learn more about C++.

Good luck and happy learning!