Home »
C++ programming language
Function overloading example based on Number of Arguments in C++
Learn: How to implement function overloading based on different number of argument in C++ programming language?
If you didn't read about the function overloading, I would recommend please read C++ function overloading before reading this article.
Function overloading based on Number of Arguments in C++
We can implement function overloading on the basis of number of arguments passed into function. Function overloading can be implementing in non-member function as well as member function of class.
Example 1
Example of non-member function based function overloading according to number of arguments is given below:
#include <iostream>
using namespace std;
void sum(int A, int B);
void sum(int A, int B, int C);
void sum(int A, int B, int C, int D);
int main()
{
sum(1,2);
sum(1,2,3);
sum(1,2,3,4);
return 0;
}
void sum(int A, int B)
{
cout<< endl << "SUM is : "<< A+B;
}
void sum(int A, int B, int C)
{
cout<< endl << "SUM is : "<< A+B+C;
}
void sum(int A, int B, int C, int D)
{
cout<< endl << "SUM is : "<< A+B+C+D;
}
Output
SUM is : 3
SUM is : 6
SUM is : 10
Example 2
Example of member function of class based function overloading according to number of arguments is given below:
#include <iostream>
using namespace std;
class funOver
{
public:
void sum(int A, int B);
void sum(int A, int B, int C);
void sum(int A, int B, int C, int D);
};
void funOver::sum(int A, int B)
{
cout<< endl << "SUM is : "<< A+B;
}
void funOver::sum(int A, int B, int C)
{
cout<< endl << "SUM is : "<< A+B+C;
}
void funOver::sum(int A, int B, int C, int D)
{
cout<< endl << "SUM is : "<< A+B+C+D;
}
int main()
{
funOver ob;
ob.sum(1,2);
ob.sum(1,2,3);
ob.sum(1,2,3,4);
return 0;
}
Output
SUM is : 3
SUM is : 6
SUM is : 10