Function part 8 (Overloading Function)
Function overloading is a feature of C++ that allows you to have two or more functions with the same name, as long as they have different parameters. This can be useful when you want to have a single function that can perform different tasks, depending on the type of data that is passed to it as an argument.
For example, this code is a set of three C++ functions that print different types of data to the console.
#include <iostream>
using namespace std;
void print(int a)
{
cout << "Integer = " << a << endl;
}
void print(float a)
{
cout << "Float = " << a << endl;
}
void print(char c)
{
cout << "Character = " << c << endl;
}
int main()
{
print(1);
print('a');
return 0;
}
The first function, print(int a), takes an integer as an argument and prints it to the console with the prefix “Integer = “.
The second function, print(float a), takes a floating-point number as an argument and prints it to the console with the prefix “Float = “.
The third function, print(char c), takes a character as an argument and prints it to the console with the prefix “Character = “.
Output:
Integer = 1 Character = a