Function Overloading in C++
Function overloading is a feature in C++ that allows you to define multiple functions with the same name but different parameters. These functions can perform similar tasks but with different types or numbers of inputs. The compiler distinguishes between overloaded functions based on the number or type of parameters.
add() that works with integers, floats, etc.#include <iostream>
using namespace std;
// Function to add two integers
int add(int a, int b) {
return a + b;
}
// Overloaded function to add three integers
int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded function to add two floats
float add(float a, float b) {
return a + b;
}
int main() {
cout << "Sum of two integers: " << add(5, 10) << endl; // Calls int add(int, int)
cout << "Sum of three integers: " << add(5, 10, 15) << endl; // Calls int add(int, int, int)
cout << "Sum of two floats: " << add(5.5f, 10.5f) << endl; // Calls float add(float, float)
return 0;
}
add() functions in this example:
int add(int, int)).int add(int, int, int)).float add(float, float)).Each function has the same name add, but they perform slightly different tasks based on the arguments passed.
Different number of parameters:
void print(int a) { cout << "Integer: " << a << endl; }
void print(int a, int b) { cout << "Two Integers: " << a << " " << b << endl; }
Different types of parameters:
void print(int a) { cout << "Integer: " << a << endl; }
void print(float a) { cout << "Float: " << a << endl; }
Different order of parameters:
void print(int a, float b) { cout << "Int and Float: " << a << ", " << b << endl; }
void print(float a, int b) { cout << "Float and Int: " << a << ", " << b << endl; }
Return type cannot be used to differentiate overloaded functions:
int add(int a, int b); // Valid
float add(int a, int b); // Invalid — only the return type is different
Parameter types, number, or order must differ:
Overloading and Default Arguments:
Function overloading allows you to define multiple functions with the same name but different parameter lists (number or type of parameters). This is useful for performing similar tasks on different types or numbers of data without having to create different function names for each case.
Open this section to load past papers