Function Overloading by Dr.afzalBadshah
Function Overloading by Dr.afzalBadshah
Class Code:
#include <iostream>
using namespace std;
class Calculator {
public:
// Function to add two integers
int add(int a, int b) {
return a + b;
}
return 0;
}
Explanation of the Main Function:
Object Creation:
Calculator cal: Creates an instance of the Calculator class.
Calling Overloaded Functions:
cal.add(5, 10)
Invokes the first add function for integers with two parameters.
Outputs: The sum of two integers is: 15.
cal.add(5, 10, 15)
Invokes the second add function for integers with three
parameters.
Outputs: The sum of three integers is: 30.
cal.add("HELLO", " WORLD!")
Invokes the third add function for string concatenation.
Outputs: The concatenation of two strings is: HELLO WORLD!.
cal.add(5.55, 6.75)
Invokes the fourth add function for double values.
Outputs: The sum of two double numbers is: 12.3.
Output of the Program:
The sum of two integers is: 15
The sum of three integers is: 30
The concatenation of two strings is: HELLO WORLD!
The sum of two double numbers is: 12.3
Key Points About Function Overloading:
Differentiation by Parameters:
Functions must differ by the number, type, or order of their
parameters.
Changing only the return type is not sufficient for function
overloading.
Compile-Time Polymorphism:
Function overloading is an example of compile-time
polymorphism, meaning the decision of which function to call is
made during compilation.
Real-Life Applications:
Allows the same operation (e.g., add) to work with different data
types or scenarios, such as adding numbers or concatenating
strings.
Conclusion:
Function overloading in C++ is a key feature of polymorphism that
enhances code reusability and readability. By allowing functions
with the same name to handle different types and numbers of
parameters, developers can write cleaner and more organized
code. In the provided example, the overloaded add functions
demonstrate how this feature can be used for multiple purposes,
from arithmetic operations to string concatenation.