C++ Function Overloading 

Function overloading is achieved when two or more functions can have the same name but with different parameter lists. That means Functions with the same name must differ in their types and number of parameters. This allows the compiler to match parameter list and choose the correct method when a number of choices exist. So, function overloading is an example of compile time polymorphism.

Advantage: Function overloading enhances the readability of the program code.

 

Example 1

Below is an example demonstrating function overloading concept with respect to different parameter types.

function_overload01.cpp

// function overloading using different types of parameters
#include <iostream>
using namespace std;

int sum(int x, int y) { // (1)
return x + y;
}

double sum(double x, double y) { // (2)
return x + y;
}

int main() {
int result1 = sum(8, 6); // call (1)
double result2 = sum(5.32, 7.25); // call (2)
cout << "INTEGER SUM: " << result1 << endl;
cout << "DECIMAL SUM: " << result2;
return 0;
}

Output:

INTEGER SUM: 14
DECIMAL SUM: 12.57

 

Example 2

Below is an example of a class demonstrating function overloading concept with regard to different number of parameters.

function_overloading02.java

// function overloading using different numbers of parameters
#include <iostream>
using namespace std;

int add(int x, int y) { // (1)
return x + y;
}

int add(int x, int y, int z) { // (2)
return x + y + z;
}

int main() {
int result1 = add(12, 23); //call (1)
int result2 = add(20, 30, 40); //call (2)
cout << "Result1: " << result1 << endl;
cout << "Result2: " << result2;
return 0;
}

Output:

Result1: 35
Result2: 90

 

 

C++ Constructor Overloading

Like functions, constructors can also be overloaded. Since all the constructors in a class have the same name as the class, they are differentiated by their parameter lists. 

Example 3

The example below shows that the Rectangle constructor is overloaded one being a default constructor and the other being a parameterized constructor. 

constructor_overload.cpp

// constructor overloading

#include <iostream>
using namespace std;

class Rectangle {

private:
int length, breadth;

public:
Rectangle(); // (1) default constructor
Rectangle(int l, int b); // (2) parameterized constructor
int getArea();
};

Rectangle :: Rectangle() {
length = 10;
breadth = 10;
}

Rectangle :: Rectangle(int l, int b) {
length = l;
breadth = b;
}

int Rectangle :: getArea() {
return length * breadth;
}

int main() {
Rectangle rect1; // (1)
Rectangle rect2(15, 12); // (2)
cout << "AREA1: " << rect1.getArea() << endl;
cout << "AREA2: " << rect2.getArea();
return 0;
}

Output:

AREA1: 100
AREA2: 180