Function overloading is an object-oriented programming feature in which two or more functions have the same name but different parameters.
The function overloading feature in C++ is used to improve code readability. It is used to save the programmer from having to remember multiple function names. Function overloading can also be treated as compile-time polymorphism.
It should be noted that function declarations that differ only in return type cannot be overloaded.
#include <iostream>
using namespace std;
void add(int x, int y)//sum of integers
{
cout << "sum = " << (x + y);
}
void add(double x, double y)//sum of double elements
{
cout << endl << "sum = " << (x + y);
}
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
sum = 12
sum = 11.5
In the above example, we can see there are two add functions but with different types of arguments, i.e, add function is overloaded, due to which the compiler can easily differentiate which one of the functions is to be executed on the function call.
#include <iostream>
using namespace std;
void add(int x, int y)//sum of two integers
{
cout << "sum = " << (x + y);
}
void add(int x, int y, int z)//sum of three integer elements
{
cout << endl << "sum = " << (x + y + z);
}
int main()
{
add(10, 2);
add(5, 6, 10);
return 0;
}
sum = 12
sum = 21
Here it is clear that add function is overloaded by changing the number of arguments, although keeping the data type same.
When we specify a default value for a parameter while declaring a function, we refer to it as the default argument. In this case, even if we call the function without specifying a value for that parameter, the function will use the default value. For instance,
#include <iostream>
using namespace std;
void add(int x, int y=9)//sum of two integers
{
cout << "sum = " << (x + y);
}
int main()
{
add(10);
add(10, 0);
add(5, 6);
return 0;
}
sum = 19
sum = 10
sum = 11
Note: also read about Inline Function in C++
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…