WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Basic · question 16 of 100

What is function overloading in C++? Can you provide an example?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

Function overloading in C++ is the ability to define multiple functions with the same name but with different parameter lists. When a function is called with a certain set of parameters, the compiler determines which version of the function to call based on the number and types of the parameters.

To overload a function in C++, you declare multiple functions with the same name but with different parameter lists. For example:

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

In this example, we have three functions with the same name ’add’, but with different parameter lists. The first function takes two integers and returns an integer, the second function takes two doubles and returns a double, and the third function takes three integers and returns an integer.

When we call the add() function with different parameters, the compiler determines which version of the function to call based on the number and types of the parameters. For example:

    int x = add(1, 2); // calls int add(int, int)
    double y = add(3.5, 2.5); // calls double add(double, double)
    int z = add(1, 2, 3); // calls int add(int, int, int)

In this example, the first call to add() with two integers calls the int add(int, int) function, the second call with two doubles calls the double add(double, double) function, and the third call with three integers calls the int add(int, int, int) function.

Function overloading is useful in C++ because it allows you to write functions with the same name that perform different tasks depending on the types and number of their parameters. This makes the code more readable and easier to use, as you can call the same function name with different parameters depending on the situation.

In summary, function overloading in C++ is the ability to define multiple functions with the same name but with different parameter lists. Function overloading is useful in C++ because it allows you to write functions with the same name that perform different tasks depending on the types and number of their parameters, making the code more readable and easier to use.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics