C++ - Function Overloading
With function overloading feature in C++, two or more functions can have the same name but different parameters. It allows the programmer to write functions to perform conceptually the same thing on different types of data without changing the name.
Example:
In the example below, three function with the same name MyFunct are created. First function takes two integer numbers as arguments and returns sum of these numbers. The second function takes two float numbers as arguments and returns sum of these numbers. The third function takes three integer numbers as arguments and returns sum of these numbers.
#include <iostream> using namespace std; int MyFunct(int x, int y); float MyFunct(float x, float y); int MyFunct(int x, int y, int z); int main (){ int a = 100, b = 10, c = 1; float p = 500.5, q = 50.05; cout<<"MyFunct(int, int) is used. Result: " <<MyFunct(a, b)<<"\n"; cout<<"MyFunct(float, float) is used. Result: " <<MyFunct(p, q)<<"\n"; cout<<"MyFunct(int, int, int) is used. Result: " <<MyFunct(a, b, c)<<"\n"; return 0; } int MyFunct(int x, int y){ return x+y; } float MyFunct(float x, float y){ return x+y; } int MyFunct(int x, int y, int z){ return x+y+z; }
The output of the above code will be:
MyFunct(int, int) is used. Result: 110 MyFunct(float, float) is used. Result: 550.55 MyFunct(int, int, int) is used. Result: 111
❮ C++ - Functions