3/19/2016

Overloading functions in c++

A program to swap two numbers(either integers or floats) by using overloading function.

#include<iostream>
using namespace std;
class temp
{
public:
void swap(int,int);
void swap(float,float);
temp()
{
cout<<"Choose one option:";
cout<<"\nSwap integers-1\nSwap floats-2\n";
}
};

void temp::swap(int no1,int no2)
{
int temp=no1;
no1=no2;
no2=temp;
cout<<"After swap:"<<no1<<" "<<no2;
}
void temp::swap(float no1,float no2)
{
float temp=no1;
no1=no2;
no2=temp;
cout<<"After swap:"<<no1<<" "<<no2;
}
int main()
{
temp aaa;
int option;
int a,b;
cin>>option;
if(option==1)
{
cout<<"Enter two integers:";
cin>>a>>b;
aaa.swap(a,b);
}
if(option==2)
{
cout<<"Enter two floats:";
foat aa,bb;
cin>>aa>>bb;
aaa.swap(aa,bb);
}
return 0;
}

Output:
Choose one option:
Swap integers-1
Swap floats-2
2
Enter two floats:4.5
6.3
After swap:6.3 4.5


…………………………………………………
…………………………………………………

A program  to find the square of a number(either integer or float) by using function overloading. 

#include<iostream>
using namespace std;
class maths
{
public:
int square(int);
float square(float);
void menu();
};

int maths::square(int a)
{
return(a*a);
}
float maths::square(float a)
{
return(a*a);
}

void maths::menu()
{
cout<<"Choose in the following options:\n";
cout<<Square of an integer no.:1\nSquare of a float no.:2\n";
}
int main()
{
maths aaa;
aaa.menu();
int option;
int x;
float y;
cin>>option;
if(option==1)
{
cout<<"Enter an integer value:";
cin>>x;
cout<<"Square="<<aaa.square(x);
}
if(option==2)
{
cout<<"Enter a float value:";
cin>>y;
cout<<"Square="<<aaa.square(y);
}
return 0;
}

Output:
Choose in the following options:
Square of an integer no.:1
Square of a float no.:2
2
Enter a float value:3.4
Square=11.56



……………………………………………………………………………



Overloading Arithmetic Operators
A program to sum the two complex number.
……………………………………………………………………………

#include<iostream>
using namespace std;
class complex
{
public:
float real;
float imag;
complex operator + (complex bbb)
{
complex sum;
sum.real=real+bbb.real;
sum.imag=imag+bbb.imag;
return(sum);
}
};
int main()
{
complex aaa,bbb,sum;
cout<<"Enter first complex no.";
cin<<aaa.real;
cin>>aaa.imag;
cout<<"Enter second complex no.";
cin>>bbb.real;
cin>>bbb.imag;
sum=aaa+bbb;
cout<<"\nSummation of two complex no.:\n";
cout<<sum.real;
if(sum.imag>=0)
{
cout<<"+i"<<sum.imag;
}
else
{
cout<<"-i"<<(-1)*sum.imag;
return 0;
}

Output:
Enter first complex no.-3 -8
Enter second complex no.5 2

Summation of two complex no.:
2-i6

…………………………………………………………………………

Overloading assignment Oprator
-----------------------------------------------------

#include<iostream>
using namespace std;
class test
{
public:
int a;
test(int num)
{
a=num;
}
test operator = (test aaa)
{
a=aaa.a;
}
void print()
{
cout<<a;
}
};

int main()
{
test aa(4);
test bb(5);
bb.operator= (aa);
cout<<"In object bb,value=";
bb.print();
return 0;
}

Output:
In object bb,value=4


………………………………………………………………………





No comments:

Post a Comment