C++ Program to Perform function overloading in C ++


January 21, 2023, Learn eTutorial
1103

What is Function overloading in C++?

In C++, Function Overloading is defined as the process of having two or more functions with the same name but different parameters. In function overloading, A function is redefined, with either different argument types or different argument numbers. A compiler can differentiate between the functions using these differences. It will increase the readability of the program because you don't need to use different names for the same action.

Perform function overloading in C ++

C++ program with different numbers of arguments in function overloading

Create a class cal and define a method add with 2 variables d and e as arguments. Return a value of d + e.

static int add(int d, int e)
{      
    return d + e;      
} 

Define another method add with 3 variables d , e, and f as arguments. Return a value of d + e + f.

static int add(int d, int e, int f)
{      
    return d + e + f;      
} 

Create an object obj for class cal and call the function to add (d, e) with the object obj using the code obj.add(10, 20)  This statement will invoke the function static int add(int d, int e) and return a value d + e.

Call the function add (d, e, f) with object obj using the code obj.add(12, 23, 20)This statement will invoke the function static int add(int d, int e, int f) and return a value, d + e + f. Display the result on the screen.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Create a class cal.

Step 4: Define a function with two arguments and return a value of the sum of the arguments.

Step 5: Define again with three arguments and  return a value of the sum of the arguments

Step 6: Call the function main

Step 7: Create an object obj for the class cal.

Step 8: Call the function with the object and pass two integers as arguments.

Step 9: Call again with the object and pass three integers as arguments

Step 10: Display the result on the screen.

Step 11: Exit 

C++ Source Code

                                          #include <iostream>    
using namespace std;    
class Cal
 {    
    public:    
static int add(int d, int e)
    {      
        return d + e;      
    }      
static int add(int d, int e, int f)      
    {      
        return d + e + f;      
    }      
};     
int main(void)
{    
    Cal obj;                                                    //     class object declaration.   
    cout<<obj.add(10, 20)<<endl;      
    cout<<obj.add(12, 20, 23);     
   return 0;    
}    
                                      

OUTPUT

30
55