C++ Function Overloading

Welcome to The Coding College! In this tutorial, we’ll explore function overloading in C++, a powerful feature that allows you to define multiple functions with the same name but different parameter lists.

What is Function Overloading?

Function overloading enables defining multiple functions with the same name but different:

  1. Number of parameters
  2. Types of parameters

C++ decides which function to call based on the arguments passed during the function call.

Benefits of Function Overloading

  1. Improved Code Readability: Using a single function name for related tasks.
  2. Enhanced Reusability: Reduce the need for creating unrelated function names.
  3. Compile-Time Polymorphism: The function is resolved at compile time, making it efficient.

Syntax

return_type function_name(parameters); // Function declaration

Example:

int add(int a, int b);            // Function to add integers
double add(double a, double b);  // Function to add doubles

Examples of Function Overloading

1. Overloading by Number of Parameters

#include <iostream>
using namespace std;

void display(int a) {
    cout << "Integer: " << a << endl;
}

void display(int a, int b) {
    cout << "Two Integers: " << a << " and " << b << endl;
}

int main() {
    display(10);       // Calls the function with one parameter
    display(20, 30);   // Calls the function with two parameters

    return 0;
}

Output:

Integer: 10  
Two Integers: 20 and 30  

2. Overloading by Parameter Types

#include <iostream>
using namespace std;

void print(int num) {
    cout << "Integer: " << num << endl;
}

void print(double num) {
    cout << "Double: " << num << endl;
}

void print(string text) {
    cout << "String: " << text << endl;
}

int main() {
    print(42);          // Calls the int version
    print(3.14);        // Calls the double version
    print("Hello!");    // Calls the string version

    return 0;
}

Output:

Integer: 42  
Double: 3.14  
String: Hello!  

3. Overloading with Default Parameters

#include <iostream>
using namespace std;

void greet(string name, string message = "Welcome!") {
    cout << "Hello, " << name << "! " << message << endl;
}

int main() {
    greet("Alice");                        // Uses default message
    greet("Bob", "Good to see you!");      // Uses custom message

    return 0;
}

Output:

Hello, Alice! Welcome!  
Hello, Bob! Good to see you!  

4. Mathematical Operations

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

int main() {
    cout << "Integer addition: " << add(5, 10) << endl;          // Calls int version
    cout << "Double addition: " << add(2.5, 3.5) << endl;       // Calls double version

    return 0;
}

Output:

Integer addition: 15  
Double addition: 6  

5. Overloading for Different Data Structures

#include <iostream>
#include <vector>
using namespace std;

void printArray(int arr[], int size) {
    cout << "Array: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

void printArray(vector<int> vec) {
    cout << "Vector: ";
    for (int val : vec) {
        cout << val << " ";
    }
    cout << endl;
}

int main() {
    int arr[] = {1, 2, 3, 4};
    vector<int> vec = {10, 20, 30, 40};

    printArray(arr, 4);   // Calls the array version
    printArray(vec);      // Calls the vector version

    return 0;
}

Output:

Array: 1 2 3 4  
Vector: 10 20 30 40  

Function Overloading with Mixed Types

You can mix types of parameters in overloaded functions.

Example: Overloaded calculateArea

#include <iostream>
using namespace std;

double calculateArea(double radius) {
    return 3.14 * radius * radius;  // Area of circle
}

int calculateArea(int length, int width) {
    return length * width;          // Area of rectangle
}

int main() {
    cout << "Circle area: " << calculateArea(5.0) << endl;          // Calls circle version
    cout << "Rectangle area: " << calculateArea(4, 5) << endl;     // Calls rectangle version

    return 0;
}

Output:

Circle area: 78.5  
Rectangle area: 20  

Rules for Function Overloading

  1. Different Parameter List: Overloaded functions must differ in the number or type of parameters.
  2. Return Type Doesn’t Matter: Functions cannot be overloaded solely based on return type.

Invalid Example:

int multiply(int a, int b);
double multiply(int a, int b); // Error: Ambiguous

Best Practices

  1. Use function overloading only when the purpose of the functions is similar.
  2. Avoid overloading functions with too many subtle differences, which might confuse users.
  3. For advanced use cases, consider templates instead of function overloading.

Explore More at The Coding College

Function overloading is just the beginning of mastering C++! For advanced topics like templates, virtual functions, and operator overloading, visit The Coding College.

Leave a Comment