Function Overloading in C++
In C, you had to name functions `print_int()`, `print_float()`, and `print_str()`. In C++, functions can share the exact same name as long as their parameter types differ.
What is it?
Function overloading is a compile-time polymorphism feature where two or more functions can have the same name if their parameter lists differ in number or type.
Why is it used?
Improves code readability and API consistency by using intuitive, uniform function names.
Detailed Explanation
Rules for Overloading:
• Functions must differ in Parameter Type, Parameter Count, or Parameter Order.
• Functions CANNOT be overloaded based on return type alone! (e.g. `int add()` and `double add()` with identical parameters is a compiler error).
• Name Mangling: The C++ compiler generates unique internal names for overloaded functions based on their parameter signatures.
Syntax Structure
Syntax Blueprint
int add(int a, int b);
double add(double a, double b);
int add(int a, int b, int c);
Code Example
CPP Code
#include <iostream>
#include <string>
// Overloaded billing calculator functions
void calculate_bill(int single_course_fee) {
std::cout << "Single Course: ₹" << single_course_fee << "\n";
}
void calculate_bill(int course1, int course2, double bundle_discount) {
int subtotal = course1 + course2;
double savings = subtotal * (bundle_discount / 100.0);
std::cout << "2-Course Combo: ₹" << (subtotal - savings)
<< " (Saved ₹" << savings << ")\n";
}
void calculate_bill(const std::string &corporate_name, int num_seats, int seat_rate) {
std::cout << "Corporate Tier: " << corporate_name
<< " (" << num_seats << " seats @ ₹" << seat_rate << ") = ₹"
<< (num_seats * seat_rate) << "\n";
}
int main() {
std::cout << "=== Function Overloading Billing System ===\n";
calculate_bill(2500);
calculate_bill(2500, 2500, 15.0); // 15% combo discount
calculate_bill("TCS Nanded Batch", 10, 2000);
return 0;
}
Explanation of the Code
• Three distinct functions share the name `calculate_bill`.
• The compiler selects the exact version based on passed argument types and counts at compile time.
Expected Output
=== Function Overloading Billing System ===
Single Course: ₹2500
2-Course Combo: ₹4250 (Saved ₹750)
Corporate Tier: TCS Nanded Batch (10 seats @ ₹2000) = ₹20000
Real-World Application
Used across math libraries (`abs(int)` vs `abs(double)`) and standard stream operators.
Common Mistakes to Avoid
• Attempting to overload functions solely by return type (compiler error).
• Creating ambiguous overloads with implicit type conversions.
Quick Practice Challenge
Write two overloaded functions `print_value(int)` and `print_value(std::string)`.
Key Takeaways
• Function overloading is resolved at compile time.
• Signatures must differ by parameter types or counts.
• Return type alone cannot distinguish overloads.