MODULE 3: FUNCTIONS & SCOPE 3.3 C++ Function Overloading (Compile-Time Polymorphism) - 10 Real-Time Examples

Industrial reference manual: Comprehensive architectural breakdown of C++ function overloading (compile-time polymorphism), method resolution rules based on parameter signatures, and 10 production-aligned real-world code implementations with outputs.

🔀 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.

1. Multi-Format Area Calculator (Different Parameter Types)
Overloads the `calculateArea` function to handle rectangles (`int`), squares (`double`), and circles.
C++ / Overloaded Area Calculator
#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;
}
--- Overloaded Area Calculations --- Rectangle (10 x 5) : 50 sq.units Square (6.5 side) : 42.25 sq.units Circle (Radius 7) : 153.94 sq.units
2. Universal Logger Function (`int`, `double`, `string`)
Overloads a `logMessage` function to output system diagnostics for different data types.
C++ / Overloaded Logger
#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;
}
--- Overloaded System Logger --- [LOG - TEXT] : System boot sequence initiated. [LOG - ERROR] : Code #404 [LOG - METRIC] : CPU Load at 84.5%
3. E-Commerce Discount Engine (Parameter Count Overloading)
Overloads `calculateDiscount` based on whether promotional coupon codes or festive bonus tiers apply.
C++ / Overloaded Discount Engine
#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;
}
--- Overloaded E-Commerce Discounts --- Tier 1 (₹5000): ₹4500.00 Tier 2 (₹5000, 20%): ₹4000.00 Tier 3 (₹5000, 20%, ₹200 bonus): ₹3800.00
4. Payment Gateway Multi-Currency Processor
Overloads `processPayment` for INR (`double`), USD (`float`), and cryptocurrency transactions (`string`).
C++ / Overloaded Payment Gateway
#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;
}
--- Overloaded Payment Processor --- [INR Gateway] Processing ₹15000.5 [USD Gateway] Processing $199.99 [Crypto Gateway] Verifying Hash: 0x8F4C...B92E
5. User Authentication Profile Search
Overloads `findUser` to search user databases via integer User ID, string Email address, or phone number (`long long`).
C++ / Overloaded User Search
#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;
}
--- Overloaded User Directory Search --- Searching database by User ID: #10482 Searching database by Email: aarav.sharma@nikitainfotech.com Searching database by Phone: +919876543210
6. Database Query Record Filter
Overloads `filterRecords` to retrieve database entries filtered by date ranges, category codes, or status flags.
C++ / Overloaded Query Filter
#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;
}
--- Overloaded Database Query Builder --- Query: SELECT * WHERE category = 'Electronics' Query: SELECT * WHERE rating BETWEEN 4 AND 5 Query: SELECT * WHERE is_active = TRUE
7. Scientific Math Utility Overloads (`power` function)
Overloads `computePower` to calculate exponentiation for integer bases and floating-point exponents.
C++ / Overloaded Exponentiation
#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;
}
--- Overloaded Math Utility --- Integer Power (2^8) : 256 Double Power (2.5^3.2): 20.4851
8. Data Serialization: Formatted Output Exporters
Overloads `exportData` to serialize records into JSON, CSV, or XML format streams.
C++ / Overloaded Exporters
#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;
}
--- Overloaded Data Exporter --- { "data": "ServerMetrics" } ID,VALUE 1,ServerMetrics
9. Automated Formatting Display System
Overloads `displayValue` to format and render currency, percentages, and standard integers.
C++ / Overloaded Formatter
#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;
}
--- Overloaded UI Formatter --- Formatted Currency : ₹48500.50 Formatted Progress : 89.4% Formatted Counter : 1420 units
10. Notification Dispatcher Overload (SMS, Email, Push)
Overloads `sendNotification` to route messages via SMS phone numbers, email addresses, or device push tokens.
C++ / Overloaded Notification Dispatcher
#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;
}
--- Overloaded Notification Dispatcher --- [SMS Gateway] To: +919876543210 | Msg: Your OTP is 4829. [Email Service] To: support@nikitainfotech.com | Subj: Security Alert [Push Notification] Token: FCM_TO... | Title: Flash Sale