Programming Tutorials

Function overloading in C++

By: Babbar Ankit in C++ Tutorials on 2009-05-30  

Function overloading is a feature in C++ that allows a function to have multiple definitions with the same name but different parameters. When a function is called, the compiler determines which version of the function to use based on the number, types, and order of the arguments passed to the function.

Here's an example of function overloading in C++:

#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() {
    int x = 5, y = 10;
    double a = 3.5, b = 7.2;
    
    cout << add(x, y) << endl; // Calls the int version of add()
    cout << add(a, b) << endl; // Calls the double version of add()
    
    return 0;
}

In this example, the add() function is defined twice, once to add two integers and once to add two doubles. When the add() function is called, the compiler decides which version to use based on the types of the arguments passed.

This feature can be useful for improving code readability and reducing the number of functions that need to be written for different data types.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)