Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
How Does Function Overloading Work?
3.
Why is Function Overloading in C++ Used?
4.
Examples of Function Overloading in C++ 
4.1.
C++
4.2.
C++
5.
Rules of Function Overloading in C++
6.
Which Function to Run When an Overloaded Function is Called?
7.
Types of Function Overloading in C++
8.
Advantages of Function Overloading in C++
9.
Disadvantages of Function Overloading in C++
10.
Causes of function overloading in C++
10.1.
1. Type conversion
10.2.
C++
10.3.
C++
10.4.
2. Function with default arguments
10.5.
C++
10.6.
3. Function with pass by reference
10.7.
C++
11.
Can the main() function be overloaded in C++?
11.1.
C++
12.
Frequently Asked Questions
12.1.
What is the minimum number of functions required to achieve function overloading in C++?
12.2.
Is function overloading a compile-time polymorphism or runtime polymorphism?
12.3.
What is the difference between function overloading and polymorphism in C++?
12.4.
How to achieve function overloading in C++?
13.
Conclusion
Last Updated: Sep 12, 2024
Easy

Function Overloading In C++

Introduction 

Function overloading is when more than one function has the same name but different signatures. In this case, the function call decides which overloaded function to run. 

Function Overloading can be achieved in the following ways:

  • A different number of parameters
  • Different data types of parameters


Also, see Literals in C, Fibonacci Series in C++

How Does Function Overloading Work?

Function overloading in C++ allows multiple functions with the same name but different parameters to coexist. The compiler differentiates these functions based on the number, types, or order of parameters. When an overloaded function is called, the compiler determines which version to execute by matching the call's arguments to the function's parameters. This feature enables more readable and intuitive code, allowing functions to handle different types of data without needing distinct names for each variant.

Why is Function Overloading in C++ Used?

Function overloading is used in C++ to enhance code readability and maintainability. It allows programmers to use the same function name for different operations, provided they differ in parameter type or count. This reduces the need for multiple function names, simplifying the interface and making the code more intuitive. Overloading also supports polymorphism, enabling functions to operate on various data types, thus promoting code reuse and reducing redundancy.

Examples of Function Overloading in C++ 

Let’s look at some examples to understand function overloading in C++.

Example 1

Function Overloading in c++ can be achieved by specifying a different number of parameters in the function definition.

Example:

  • C++

C++

#include<iostream>  
using namespace std;

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

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

int main() {
display(5);
display(5,10);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

a = 5
a = 5 and b = 10

 

You can try and compile with the help of online c++ compiler.
In the above program, there are two display() functions. The first one consists of a single int parameter and the second one has two int parameters. display() function gets overloaded in this case because of a different number of parameters.

Example 2

Function Overloading in c++ can be achieved by specifying different types of parameters in the function definition.

  • C++

C++

#include<iostream>  
using namespace std;

// function with (int,int) parameters
void multiply(int a, int b) {
cout << "a * b = "<<a*b<<endl;
}

// function with (double,double) parameters
void multiply(double a, double b) {
cout << "a * b = "<<a*b<<endl;
}

// function with (int,double) parameters
void multiply(int a, double b) {
cout << "a * b = "<<a*b<<endl;
}

// function with (double,int) parameters
void multiply(double a, int b) {
cout << "a * b = "<<a*b<<endl;
}

int main() {
multiply(5, 10);
multiply(1.2,0.5);
multiply(3,0.4);
multiply(0.5, 3);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

a * b = 50
a * b = 0.6
a * b = 1.2
a * b = 1.5


In the above program, there are four multiply() functions. All four have different types of data types in a different order. The multiply() function gets overloaded in this case because of different parameter types.

Rules of Function Overloading in C++

  • Different Parameter Types: Functions must have different parameter types.
  • Number of Parameters: Functions can have a different number of parameters.
  • Parameter Order: Functions can have parameters in different orders.
  • Return Type Ignored: The return type is not considered for overloading. Functions cannot be overloaded solely on different return types.
  • Default Arguments: Functions with default arguments must be considered carefully, as they might conflict with other overloaded versions.
  • Scope Considerations: Function overloading is applied within the same scope. Functions in different scopes (like base and derived classes) do not affect each other.
  • Const and Non-Const Parameters: Functions can be overloaded based on const and non-const parameters.
  • Pointer and Reference Parameters: Functions can be overloaded with pointer and reference parameters.
  • Ellipsis (…) Parameters: Functions can be overloaded if they differ by including an ellipsis (…) parameter.

Which Function to Run When an Overloaded Function is Called?

When an overloaded function is called, the compiler determines the most appropriate function definition to use, by comparing the number of arguments and argument types you have used to call the function. This process of selecting the most appropriate overloaded function is called overload resolution.

The steps of overload resolution are:

  • Find suitable functions via name lookup. These functions are called candidate functions.
  • Remove invalid candidate functions from the list. The left out functions are called viable functions. A candidate function becomes invalid when:
    • The passed argument count does not match the parameter list.
    • Passed arguments types do not match the function parameter.
  • Viable functions are then ranked.
    • Ranking order: Exactly match parameters >  parameters matched after standard conversions >  parameters matched after user-defined conversions
  • If the best match is found from the viable function list, then that function is executed; else the compiler returns an error.
     

Note: Function overloading is independent of the return type.

Types of Function Overloading in C++

There are two types of function overloading in C++.

  1. Compile-Time Overloading: Compile-time overloading, also known as static polymorphism, occurs when the function to be invoked is determined at compile time. This is achieved through function overloading and operator overloading, allowing multiple functions with the same name but different parameters to coexist.
  2. Runtime Overloading: Runtime overloading, also known as dynamic polymorphism, involves determining the function to be invoked at runtime. This is typically achieved through virtual functions in base and derived classes, enabling function overriding where derived classes provide specific implementations of functions declared in the base class.

Advantages of Function Overloading in C++

Some of the benefits of function overloading are:

  • Programs execution becomes faster.
  • Smooth and simple code flow.
  • Code maintenance becomes easier.
  • Improves code readability.
  • Saves memory space.
  • Code reusability achieved.
  • It brings flexibility to the code.
  • It can perform different operations, and hence it eliminates the use of different function names for the same kind of operations.

Disadvantages of Function Overloading in C++

Some of the disadvantages of function overloading are:

1. Functions with different return types cannot be overloaded as they can have the same parameter definition.

Consider the case below:

public void num(int a) {
cout << "a = "<<a<<endl;
}

public int num(int a) {
return a + 10;
}


In this case, the compiler cannot decide which function to call as both have the same parameter definition even after having different return types.

2. It cannot overload functions with the same name and parameter if any one of them is a static member function declaration.

The static member functions can’t be overloaded because the definition must be the same for all class instances. If an overloaded function has many definitions, none of them can be made static

Causes of function overloading in C++

The situation in which the compiler is unable to decide the appropriate overloaded function is called overloading ambiguity. In that case, the compiler won’t run the program.

Overloading ambiguity occurs in the following cases:

1. Type conversion

In C++, some data types will get automatically converted to some other data type if the suffix is not mentioned. In that case, the compiler cannot decide which function to call, and an ambiguity error occurs.

  • C++

C++

#include<iostream>  
using namespace std;

void function(float) {
cout << "Data Type: float\n";
}

void function(int) {
cout << "Data Type: int\n";
}

int main() {
function(1.0);
function(1);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Error:

error image


In C++, all floating-point constants are considered as double unless explicitly specified by a suffix, so the above code generates a type conversion error.  To overcome this problem, we can add a suffix to the passed value.

  • C++

C++

#include<iostream>  
using namespace std;

void function(float a) {
cout << "Data Type: float\n";
}

void function(int a) {
cout << "Data Type: int\n";
}

int main() {
// float argument passed
function(1.0f);
// int argument passed
function(1);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

output


2. Function with default arguments

When a function is overloaded with a default argument, the compiler gets confused if another function satisfies the parameter conditions.

In the example below, when add(a) is called , both add(int a) and add(int a, int b = 10) conditions are fulfilled. In this case, the compiler cannot select which function to call and produces an ambiguity error.

Example:

  • C++

C++

#include<iostream>  
using namespace std;

int add(int a) {
int b = 10;
return a + b;
}

// function contains a default argument
int add(int a, int b = 10) {
return a + b;
And }

int main() {
int a = 5;
cout << "a + b = "<<add(a)<<endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Error:

error


3. Function with pass by reference

When a function is overloaded with a reference parameter, the compiler gets confused as there is no syntactical difference between both functions.

  • C++

C++

#include<iostream>  
using namespace std;

void display(int a) {
cout << "a = "<<a<<endl;
}

void display(int &a) {
cout << "a = "<<a<<endl;
}

int main() {
int a = 5;
display(a);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Error:

error


There is no syntactical difference between display(a) and display(&a). And in this case, the compiler will not be able to decide which function to call, resulting in an error.

Check out this article - Compile Time Polymorphism

Can the main() function be overloaded in C++?

Yes, the main() function can be overloaded in C++. To overload the main() function, we have to use a class and declare the main() function as a member function.

Example:

  • C++

C++

#include <iostream>
using namespace std;

// create a Main class and declare main() as member function
class Main {
public:
int main(int a) {
cout<<"a = "<<a<<endl;
return 0;
}

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

int main() {
Main object;
object.main(5);
object.main(5,10);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

a = 5
a = 5; b = 10

Must Read Lower Bound in C++

Frequently Asked Questions

What is the minimum number of functions required to achieve function overloading in C++?

At least two functions with the same name and different parameter signature is required to achieve function overloading in C++.

Is function overloading a compile-time polymorphism or runtime polymorphism?

Function overloading is a form of compile-time polymorphism in C++. The decision about which overloaded function to call is made at compile time based on the function signatures and argument types.

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

Function overloading is a type of compile-time polymorphism where multiple functions have the same name but different parameters. Polymorphism broadly includes both compile-time (overloading) and runtime (overriding) methods, allowing methods to behave differently based on the object's context or arguments.

How to achieve function overloading in C++?

Function overloading in C++ can be achieved by declaring more than one function has the same name but with different numbers and types of parameters.

Conclusion

This blog attempted to give a detailed explanation of function overloading in C++. Concepts like overloading resolution, overloading ambiguity, polymorphism have been covered along with some examples of function overloading in C++.

Recommended Readings: 

Live masterclass