If you want to remember something for life, find the why behind it.
We hear a lot about function overloading. But hardly many know why it is important and what is the use of it.
I have taken 100s of interviews, when I ask candidates about function overloading. Everyone tells me about it.
But when I asked why we need function overloading, even the candidate having 7+ years of experience doesn’t have an answer.
If you don’t know the practical use, your technical knowledge has zero value.
Function overloading in C++ allows you to define multiple functions with the same name but different parameter lists within the same scope.
This provides flexibility by enabling a function to perform different tasks based on the number or types of its parameters.
Let’s say you have to write a function to find the average of two numbers (says get_average()
).
#include <iostream> double get_average(double num1, double num2) { return (num1 + num2) / 2.0; } int main() { double average = get_average(34, 56); std::cout << "Average of two numbers: " << average << std::endl; return 0; }
Output:
Average of two numbers: 45
You can write another function with the same name to find the average of the array.
#include <iostream> // 1st fuction to find the average of two numbers double get_average(double num1, double num2) { return (num1 + num2) / 2.0; } // 2nd fuction to find the average of array double get_average(const double arr[], int size) { double sum = 0.0; for (int i = 0; i < size; ++i) { sum += arr[i]; } return sum / size; } int main() { //Calculate the average of two numbers double average_num = get_average(34, 56); std::cout << "Average of two numbers: " << average_num << std::endl; // Initialize an array with predefined values const int size = 5; double numbers[size] = {10.5, 20.5, 30.5, 40.5, 50.5}; // Calculate the average of array of numbers double average_array = get_average(numbers, size); std::cout << "Average of array: " << average_array << std::endl; return 0; }
Output:
Average of two numbers: 45 Average of array: 30.5
While calling a function if you pass two integers, the first function is called. If you pass an array of numbers to find the average, a second function will be called.
It enhances code readability and makes it more intuitive for developers to use the same function name with similar purposes.
I tried to explain it with very simple examples. If you have any doubts or want to share your thoughts, write in the comment section below.
I felt compelled to comment. Thanks for explaining it in very easy language.
You’re welcome!