Function Overloading in C++

Problem Statement: Function overloading in c++. To solve different problems with the help of function overloading.

Examples:

Example 1: To find the area of circle, triangle, 
square and rectangle using function overloading.

Explanation: Here we will code a program which 
will use the overloaded function (area) to find 
the solution of the given example.

Example 2: To find the multiplication of 2 and 3 
numbers with the help of the same code.

Input : 5,2 
Output: 10
Explanation: The function with 2 inputs will 
multiply both of them and will give the output 
on the screen.

Input: 5,4,3
Output: 60 
Explanation: The function with 3 inputs will 
multiply all of them and will give the output 
on the screen.

Approach: C++ allows us to use the same function in the same program but with different numbers and types of arguments. In other words, it is a feature of object-oriented programming where two or more functions can have the same name but different parameters, this feature is known as function overloading.

Conditions required for a function to be known as an overloaded function are :

  1. Different types of parameter
  2. Different number of parameter 

Advantages of function overloading are:

  1. Memory space is saved due to reusability.
  2. The readability and consistency of the program become good.
  3. It allows us to get different behavior with the same function name.
  4. Maintaining and debugging code becomes easy.

CODE FOR EXAMPLE 1

C++ Code

#include<iostream>
using namespace std;
const float pi=3.14;

float area(float n,float b,float h)
{
    float ar;
    ar=n*b*h;
    return ar;
}

float area(float r)
{
    float ar;
    ar=pi*r*r; 
    return ar;
}

float area(float l,float b)
{
    float ar;
    ar=l*b;
    return ar;
}

int main()
{
    float b,h,r,l;
    float show;
 
    show=area(0.5,4,5);
    cout<<"The area of the Triangle is "<<show<<endl;
    show=area(12);
    cout<<"The area of the Circle is "<<show<<endl;
    show=area(7,9);
    cout<<"The area of the Rectangle is "<<show<<endl;
    
    return 0;
}

Output:

The area of the Triangle is 10
The area of the Circle is 452.16
The area of the Rectangle is 63

CODE FOR EXAMPLE 2

C++ Code

#include <iostream>
using namespace std;
void mult(int a, int b)
{
    cout << "multiplication of 2 numbers are: " << (a*b);
}
 
void mult(int a, int b,int c)
{
    cout << endl << "Multiplication of 3 numbers are: " << (a*b*c);
} 

int main()
{
    mult(5, 2);
    mult(5,4,3);
    return 0;
}

Output:

multiplication of 2 numbers are: 10
Multiplication of 3 numbers are: 60

Special thanks to AYUSH KUMAR for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this articleIf you want to suggest any improvement/correction in this article please mail us at [email protected]