blog
blog copied to clipboard
C++ Overloading Functions
Concept: Two or more functions may have the same name, as long as their parameter lists are different.
Recall that a class can have more than one constructor, but all constructors of a class have the same name (but different set of parameters), which is the name of the class. This case is an example of overloading a function.
Example 1 of 2
// This program uses overloaded functions.
#include <iostream>
using namespace std;
float average(float, float);
float average(float, float, float);
int main() {
cout << average(0.1, 0.2, 0.3) << endl; // 0.2
cout << average(4.0, 5.0) << endl; // 4.5
return 0;
}
float average(float num1, float num2) {
return (num1 + num2) / 2;
}
// Overload function average:
float average(float num1, float num2, float num3) {
return (num1 + num2 + num3) / 3;
}
Example 2 of 2
// This program uses overloaded functions.
#include <iostream>
using namespace std;
// Function prototypes
int square(int);
double square(double );
int main() {
cout << square(12) << endl; // 144
cout << square(3.1415) << endl; // 9.86902
return 0;
}
int square(int number) {
return number * number;
}
//*************************************************
// Definition of overloaded function square. *
// This function uses a double parameter, number. *
// It returns the square of number as a double. *
//*************************************************
double square(double number) {
return number * number;
}