Function overloading

Function overloading

Function overloading

Function overloading in C++ allows you to define multiple functions with the same name but different parameter lists. This allows you to use the same name for similar functions that perform similar tasks but with different inputs. The compiler distinguishes between these functions based on the number, types, and order of their parameters.

Here’s an example of function overloading:

				
					#include<iostream>

//Function to add two integers

int add(int a, int b) {

    return a + b;

 }

//Function to add three integers

int add(int a, int b, int c) {

    return a + b + c;

}

//Function to add two double-precision floating-point numbers

double add(double a, double b) {

    return a + b;

}           

int main() {

    int x = 5, y = 7, z = 9;

    double d1 = 3.14, d2 = 2.71;

   std::cout << "The sum of "<< x << " and " << y << " is "<< add(x, y) << std::endl;

   std::cout << "The sum of "<< x << ", " << y << ", and "<< z << " is " << add(x, y, z) << std::endl;

    std::cout << "The sum of " << d1 << " and " << d2 << " is "<< add(d1, d2) << std::endl;
return 0; 
}
​
				
			

In this example, we define three functions with the same name add, but with different parameter lists.

The first add function takes two integers as input and returns their sum as an integer. The second add function takes three integers as input and returns their sum as an integer. The third add function takes two double-precision floating-point numbers as input and returns their sum as a double.

In the main function, we call each of these functions with different input values, and the compiler knows which version of the function to use based on the types and number of arguments.

Function overloading can help simplify your code by allowing you to use the same name for similar functions, which can make your code easier to read and maintain.

Join To Get Our Newsletter
Spread the love