Function Overloading is defined as the process of having two or more function with the same name, but different in parameters is known as function overloading. In function overloading, the function is redefined by using either different types of arguments or a different number of arguments. It is only through these differences compiler can differentiate between the functions.
For example:
// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Overloaded functions may or may not have different return
types but they must have different arguments. For example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and
the same number of arguments. Hence, the compiler will throw an error.
Example 1:
#include <iostream>
using namespace std;
// Function to calculate the area of a rectangle
int calculateArea(int length, int width) {
return length * width;
}
// Function to calculate the area of a square
int calculateArea(int side) {
return side * side;
}
// Function to calculate the area of a circle
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
int main() {
int length, width, side;
double radius;
// Area of a rectangle
cout << "Enter length and width of the rectangle: ";
cin >> length >> width;
cout << "Area of rectangle: " << calculateArea(length, width) << endl;
// Area of a square
cout << "Enter the side of the square: ";
cin >> side;
cout << "Area of square: " << calculateArea(side) << endl;
// Area of a circle
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "Area of circle: " << calculateArea(radius) << endl;
return 0;
}
Output:
Enter length and width of the rectangle: 20 10
Area of rectangle: 200
Enter the side of the square: 12
Area of square: 144
Enter the radius of the circle: 5
Area of circle: 78.5397
Process returned 0 (0x0) execution time : 20.163 s
Press any key to continue.
Example 2:
#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add two floating-point numbers
double add(double a, double b) {
return a + b;
}
// Function to concatenate two strings
string add(string a, string b) {
return a + b;
}
int main() {
// Adding two integers
int int1 = 5, int2 = 10;
cout << "Sum of integers: " << add(int1, int2) << endl;
// Adding two floating-point numbers
double double1 = 5.5, double2 = 10.5;
cout << "Sum of doubles: " << add(double1, double2) << endl;
// Concatenating two strings
string str1 = "Hello, ", str2 = "World!";
cout << "Concatenated string: " << add(str1, str2) << endl;
return 0;
}
Output:
Sum of integers: 15
Sum of doubles: 16
Concatenated string: Hello, World!
Process returned 0 (0x0) execution time : 3.090 s
Press any key to continue.
No comments:
Post a Comment