Geek Slack

Learn C++
About Lesson


C++ Function Overloading


C++ Function Overloading

In C++, function overloading allows you to define multiple functions with the same name but different parameter lists. The compiler determines which function to call based on the number and types of arguments passed to it. Function overloading enables you to perform similar operations on different data types or numbers of arguments.

1. Overloading with Different Parameter Types

Example of function overloading with different parameter types:

#include <iostream>

// Function declarations
void display(int num);
void display(double num);

int main() {
    int x = 5;
    double y = 3.14;

    // Function calls with different arguments
    display(x);
    display(y);

    return 0;
}

// Function definitions
void display(int num) {
    std::cout << "Integer value: " << num << std::endl;
}

void display(double num) {
    std::cout << "Double value: " << num << std::endl;
}

2. Overloading with Different Number of Parameters

Example of function overloading with different numbers of parameters:

#include <iostream>

// Function declarations
void greet();
void greet(std::string name);

int main() {
    // Function calls with different arguments
    greet();
    greet("Alice");

    return 0;
}

// Function definitions
void greet() {
    std::cout << "Hello!" << std::endl;
}

void greet(std::string name) {
    std::cout << "Hello, " << name << "!" << std::endl;
}

3. Overloading with Different Const Qualifiers

Example of function overloading with different const qualifiers:

#include <iostream>

// Function declarations
void print(const char *str);
void print(char *str);

int main() {
    const char *msg1 = "Hello, const!";
    char msg2[] = "Hello, non-const!";

    // Function calls with different arguments
    print(msg1);
    print(msg2);

    return 0;
}

// Function definitions
void print(const char *str) {
    std::cout << str << std::endl;
}

void print(char *str) {
    std::cout << str << std::endl;
}

Conclusion

Function overloading in C++ enhances code readability and flexibility by allowing you to define multiple functions with the same name but different parameter lists. This chapter covered overloading functions with different parameter types, different numbers of parameters, and different const qualifiers. Understanding function overloading enables you to design more versatile and expressive C++ programs, accommodating various data types and argument configurations.

Join the conversation