Example 1: Function Overloading by Number of Arguments
A C++ code having a Calculator class with function overloading (multiple add
methods).
Here’s the full working program:
#include <iostream>
using namespace std;
// Calculator class demonstrating Function Overloading
class Calculator {
public:
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Function to add two doubles
double add(double a, double b) {
return a + b;
}
};
int main() {
Calculator calc;
cout << "Sum of 2 and 3 (int): " << calc.add(2, 3) << endl;
cout << "Sum of 2, 3 and 5 (int): " << calc.add(2, 3, 5) << endl;
cout << "Sum of 2.5 and 3.5 (double): " << calc.add(2.5, 3.5) << endl;
return 0;
}
Output :
Sum of 2 and 3 (int): 5 Sum of 2, 3 and 5 (int): 10
Sum of 2.5 and 3.5 (double): 6
This is an ideal case of Function Overloading in C++ - the add function acts differently, depending on the arguments and quantity of the arguments.
Example 2: Function Overloading by Type of Arguments
A C++ code having Print class with function overloading (
display
function works for int
, double
, and string
).Here’s the full working program:
#include <iostream>
using namespace std;
class Print {
public:
void display(int a) {
cout << "Integer: " << a << endl;
}
void display(double d) {
cout << "Double: " << d << endl;
}
void display(string s) {
cout << "String: " << s << endl;
}
};
int main() {
Print p;
p.display(10); // Calls int version
p.display(3.14); // Calls double version
p.display("Hello"); // Calls string version
return 0;
}
Output:Integer: 10
Double: 3.14
String: Hello
This is another good example of function overloading in C++.
In this case the name of the function display is the same, but the parameter type determines which one to call.
In this case the name of the function display is the same, but the parameter type determines which one to call.
Thanks for reading 💗!
⮕ Share it with others who might benefit.
⮕ Leave a comment with your thoughts or questions—I’d love to hear from you.
⮕ Follow/Subscribe to the blog for more helpful guides, tips, and insights.
Comments
Post a Comment