🔀 Mastering C++ Function Overloading: Compile-Time Polymorphism
Function overloading is a feature in C++ that allows you to create multiple functions with the exact same name, provided their parameter signatures (number, type, or order of parameters) are distinct. The compiler resolves which specific function to invoke at compile time based on the arguments supplied.
⚙️ Overloading Rules
- Different Data Types: Functions can accept `int`, `double`, `string`, etc., under the same name.
- Different Parameter Counts: Varying the number of arguments allows flexible overloading.
- Signature Distinction: Changing *only* the return type is **invalid** and causes a compilation error.
💡 Key Benefits
- Code Readability: Eliminates the need for separate function names (e.g., `printInt`, `printDouble`).
- Intuitive APIs: Clean interfaces for mathematical operations, formatting, and logging.
📊 End-to-End Compile-Time Overload Resolution Workflow Diagram
1. Function Invocation
Caller calls function with specific argument types (`print(42)`).
2. Compiler Signature Match
Compiler inspects argument types and count against available overloads.
3. Exact Match / Promotion
Resolves exact match or applies standard type promotions.
6. Binary Generation
Correct function memory address bound into final machine binary.
5. Ambiguity Check
Fails compilation if multiple overloads match ambiguously.
4. Unique Binding
Binds call to the exact overloaded function body.
#include <iostream>
#include <iomanip>
using namespace std;
// Overload 1: Rectangle area (int, int)
int calculateArea(int length, int width) {
return length * width;
}
// Overload 2: Square area (double)
double calculateArea(double side) {
return side * side;
}
// Overload 3: Circle area (double radius with flag)
double calculateArea(double radius, bool isCircle) {
const double PI = 3.1415926535;
return PI * radius * radius;
}
int main() {
cout << "--- Overloaded Area Calculations ---" << endl;
cout << "Rectangle (10 x 5) : " << calculateArea(10, 5) << " sq.units" << endl;
cout << "Square (6.5 side) : " << fixed << setprecision(2) << calculateArea(6.5) << " sq.units" << endl;
cout << "Circle (Radius 7) : " << calculateArea(7.0, true) << " sq.units" << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void logMessage(string msg) {
cout << "[LOG - TEXT] : " << msg << endl;
}
void logMessage(int errorCode) {
cout << "[LOG - ERROR] : Code #" << errorCode << endl;
}
void logMessage(double cpuUsage) {
cout << "[LOG - METRIC] : CPU Load at " << cpuUsage << "%" << endl;
}
int main() {
cout << "--- Overloaded System Logger ---" << endl;
logMessage("System boot sequence initiated.");
logMessage(404);
logMessage(84.5);
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
// 1 Parameter: Standard flat discount
double calculateDiscount(double price) {
return price * 0.90; // 10% off
}
// 2 Parameters: Custom discount percentage
double calculateDiscount(double price, double discountPercent) {
return price - (price * (discountPercent / 100.0));
}
// 3 Parameters: Custom discount percentage + cashback bonus
double calculateDiscount(double price, double discountPercent, double cashbackBonus) {
double discounted = price - (price * (discountPercent / 100.0));
return discounted - cashbackBonus;
}
int main() {
cout << "--- Overloaded E-Commerce Discounts ---" << endl;
cout << "Tier 1 (₹5000): ₹" << fixed << setprecision(2) << calculateDiscount(5000.0) << endl;
cout << "Tier 2 (₹5000, 20%): ₹" << calculateDiscount(5000.0, 20.0) << endl;
cout << "Tier 3 (₹5000, 20%, ₹200 bonus): ₹" << calculateDiscount(5000.0, 20.0, 200.0) << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void processPayment(double inrAmount) {
cout << "[INR Gateway] Processing ₹" << inrAmount << endl;
}
void processPayment(float usdAmount) {
cout << "[USD Gateway] Processing $" << usdAmount << endl;
}
void processPayment(string cryptoHash) {
cout << "[Crypto Gateway] Verifying Hash: " << cryptoHash << endl;
}
int main() {
cout << "--- Overloaded Payment Processor ---" << endl;
processPayment(15000.50); // Calls double version
processPayment(199.99f); // Calls float version
processPayment("0x8F4C...B92E"); // Calls string version
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void findUser(int userId) {
cout << "Searching database by User ID: #" << userId << endl;
}
void findUser(string email) {
cout << "Searching database by Email: " << email << endl;
}
void findUser(long long phoneNumber) {
cout << "Searching database by Phone: +" << phoneNumber << endl;
}
int main() {
cout << "--- Overloaded User Directory Search ---" << endl;
findUser(10482);
findUser("aarav.sharma@nikitainfotech.com");
findUser(919876543210LL);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void filterRecords(string category) {
cout << "Query: SELECT * WHERE category = '" << category << "'" << endl;
}
void filterRecords(int minRating, int maxRating) {
cout << "Query: SELECT * WHERE rating BETWEEN " << minRating << " AND " << maxRating << endl;
}
void filterRecords(bool isActiveOnly) {
cout << "Query: SELECT * WHERE is_active = " << (isActiveOnly ? "TRUE" : "FALSE") << endl;
}
int main() {
cout << "--- Overloaded Database Query Builder ---" << endl;
filterRecords("Electronics");
filterRecords(4, 5);
filterRecords(true);
return 0;
}
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int computePower(int base, int exponent) {
return pow(base, exponent);
}
double computePower(double base, double exponent) {
return pow(base, exponent);
}
int main() {
cout << "--- Overloaded Math Utility ---" << endl;
cout << "Integer Power (2^8) : " << computePower(2, 8) << endl;
cout << "Double Power (2.5^3.2): " << fixed << setprecision(4) << computePower(2.5, 3.2) << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void exportData(string data, bool asJson) {
if (asJson) {
cout << "{ \"data\": \"" << data << "\" }" << endl;
} else {
cout << "<xml><data>" << data << "</data></xml>" << endl;
}
}
void exportData(string data, char delimiter) {
cout << "ID" << delimiter << "VALUE" << endl;
cout << "1" << delimiter << data << endl;
}
int main() {
cout << "--- Overloaded Data Exporter ---" << endl;
exportData("ServerMetrics", true); // JSON export
exportData("ServerMetrics", ','); // CSV export
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
void displayValue(double currencyVal, string currencySymbol) {
cout << "Formatted Currency : " << currencySymbol << fixed << setprecision(2) << currencyVal << endl;
}
void displayValue(float percentageVal) {
cout << "Formatted Progress : " << fixed << setprecision(1) << percentageVal << "%" << endl;
}
void displayValue(int countVal) {
cout << "Formatted Counter : " << countVal << " units" << endl;
}
int main() {
cout << "--- Overloaded UI Formatter ---" << endl;
displayValue(48500.50, "₹");
displayValue(89.4f);
displayValue(1420);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void sendNotification(long long mobileNumber, string message) {
cout << "[SMS Gateway] To: +" << mobileNumber << " | Msg: " << message << endl;
}
void sendNotification(string emailAddress, string subject, string body) {
cout << "[Email Service] To: " << emailAddress << " | Subj: " << subject << endl;
}
void sendNotification(string pushToken, string title, string payload, bool isPush) {
cout << "[Push Notification] Token: " << pushToken.substr(0, 6) << "... | Title: " << title << endl;
}
int main() {
cout << "--- Overloaded Notification Dispatcher ---" << endl;
sendNotification(919876543210LL, "Your OTP is 4829.");
sendNotification("support@nikitainfotech.com", "Security Alert", "New login detected.");
sendNotification("FCM_TOKEN_998124XYZ", "Flash Sale", "50% OFF today!", true);
return 0;
}