Function Overloading
Here’s a breakdown of function overloading:
Key Points:
- Function Name: The functions share the same name.
- Parameter Lists: The parameter lists (data types and order) must be different. This distinction tells the compiler which function to call based on the arguments provided.
- Return Type: The return type can be the same or different for overloaded functions.
Benefits:
- Code Readability: Function overloading improves code readability by using the same name for related functionalities with different parameter sets. This makes the code more intuitive and easier to understand.
- Flexibility: It allows you to handle various data types and argument combinations within a single function concept.
- Reusability: By overloading functions, you can promote code reuse without cluttering the namespace with functions that differ only by parameter lists.
Example:
#include <iostream>
void PrintNumber(int num) {
std::cout << "Integer: " << num << std::endl;
}
void PrintNumber(double num) {
std::cout << "Double: " << num << std::endl;
}
int main() {
PrintNumber(42); // Calls the function with integer argument
PrintNumber(3.14); // Calls the function with double argument
return 0;
}
In this example:
- We have two
PrintNumber
functions, one for integers and another for doubles.
- The compiler identifies which function to call based on the argument type passed in
main
.
Things to Consider:
Further Exploration:
- Function overloading is a fundamental concept in C++.
- You can explore more complex scenarios involving multiple parameters and const-correctness to gain a deeper understanding of its capabilities.
- Remember, using function overloading effectively can lead to cleaner, more maintainable, and expressive C++ code.
Link to Sample Program
Function overloading
Assignment Due on 22 October 2024
- You are provided an incomplete implementation of the Point Class
- Your have to Implement the overloaded functions:
- A distance() function that calculates the distance of a Point object from the origin O(0,0).
- A distance(const Point& other) function that calculates the distance between two points.
- A midpoint() function that calculates the midpoint between the point and the origin O(0,0).
- A midpoint(const Point& other) function that calculates the midpoint between two points.