Method overloading in C++


Method overloading

  • Method overloading means we can use same method with different number of
    argument and different data types.
  • Method overlaoding is similar as function overloading. Methods and functions
    both arethe same thing.
  • So if you know function overloading, method overloading is same.
  • The benefit of method overloading is that we can use the same name of method
    for different purpose.

Example :


#include <iostream.h>
#include <conio.h>

class Addition
{
private:

int a;
int b;
float c;
float res;

public :

void sum(int x, int y)
{
a=x;
b=y;

res=a+b;
}

void sum(int x, int y,float z) //overloaded function
{
a=x;
b=y;
c=z;

res=a+b+c;
}

void display()
{
cout<<"sum is :\n" << res;
}

};

void main()
{
clrscr();

Addition add;

cout<<"Calling the sum function :\n\n";
add.sum(2,4);
add.display();

cout<<"\n\nCalling the overloaded sum function :\n\n";
add.sum(2,4,5.5);
add.display();

getch();
}

Output :










Description :

Here sum() is overloaded as :

sum(int x,int y)--two parameters are passed both having int data type

sum(int x,int y,float z)--3 parameters are passed having different data types. Two have int
& one have float, but still the functioning is same that is addition.

Hence the number pf parameters and data types are different, so this proves the method overloading.

0 comments:

Post a Comment