Function Overloading in C++

C++ Function Overloading

Function Overloading in C++ is essentially a feature of C++ where in a program, we can write various functions with the same name but different parameters. Depending upon the argument used as passed on value an appropriate function is called by the compiler to be executed.

Example –

  • void myFunction()
  • Void myFunction(int x)
  • Void myFunction(int x, int y)
  • Void myFunction(double x)
  • Void myFunction(char x)

The above functions will get overloaded, and depending upon the passed value, as argument. One function will be chosen by the compiler.

Function Overloading is an example of compile time polymorphism.

Function Overloading in C++

Example of Function Overloading in C++

Let us look at the following example to understand the same clearly –

#include <iostream> 
using namespace std;

void myFunction(int x) {
cout << "Printing int " << x << endl;
}
void myFunction(int x, int y) {
cout << "Printing multiple int values " << x;
cout << "and" << y << endl;
}
void myFunction(double x) {
cout << " Printing double " << x << endl;
}

void myFunction(char const *x) {
cout << " Printing char " << x << endl;
}
int main() {
myFunction(10);
myFunction(10,20);
myFunction(20.10);
myFunction(10.10);
myFunction("ten");
return 0;
}

Please Login/Signup to comment