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.

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 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 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.