Mark As Completed Discussion

Function Overloading

In C++, function overloading is a feature that allows you to define multiple functions with the same name but different parameters. This means that you can have multiple functions with the same name in the same scope, as long as they have different parameter lists.

Function overloading is useful when you want to perform the same operation on different data types or with different parameter combinations.

Here's an example of function overloading in C++:

TEXT/X-C++SRC
1#include <iostream>
2
3using namespace std;
4
5// Function overloading
6int add(int a, int b) {
7  return a + b;
8}
9
10float add(float a, float b) {
11  return a + b;
12}
13
14int main() {
15  int num1 = 10;
16  int num2 = 20;
17  float num3 = 5.5;
18  float num4 = 2.5;
19
20  int sum1 = add(num1, num2);
21  float sum2 = add(num3, num4);
22
23  cout << "The sum is: " << sum1 << endl;
24  cout << "The sum is: " << sum2 << endl;
25
26  return 0;
27}

In this example:

  • We have two functions named add, one that takes two integers as parameters and returns an integer, and another that takes two floats as parameters and returns a float.
  • In the main function, we call the add function with different parameters.
  • Depending on the parameters used, the appropriate function is called and the correct sum is calculated and displayed.

When you run the code, the output will be:

SNIPPET
1The sum is: 30
2The sum is: 8
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment