Wednesday, July 20, 2011

Implementation of friend function

PROBLEM:
create two classes truck and car each containing speed of vehicle,mileage,weight and price.
write a program that can read and compare the values from two classes.use friend function for comparision.

PROGRAM:


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

class car;
class truck
{
private:
float speed,mileage,wt,price;
public:
void input()
{
cout<<"enter the speed"<<endl;
cin>>speed;
cout<<"enter the mileage"<<endl;
cin>>mileage;
cout<<"enter the weight"<<endl;
cin>>wt;
cout<<"enter the price"<<endl;
cin>>price;
}

void display()
{
cout<<"speed is: "<<speed<<endl;
cout<<"mileage is: "<<mileage<<endl;
cout<<"weight is: "<<wt<<endl;
cout<<"price is: "<<price<<endl;
}

friend void compare(truck &t,car &c);
};

class car
{
private:
float speed,mileage,wt,price;
public:
void input()
{
cout<<"enter the speed"<<endl;
cin>>speed;
cout<<"enter the mileage"<<endl;
cin>>mileage;
cout<<"enter the weight"<<endl;
cin>>wt;
cout<<"enter the price"<<endl;
cin>>price;
}
void display()
{
cout<<"speed is: "<<speed<<endl;
cout<<"mileage is: "<<mileage<<endl;
cout<<"weight is: "<<wt<<endl;
cout<<"price is: "<<price<<endl;
}

friend void compare(truck &t,car &c);
};


void compare(truck &t,car &c)
{
if(t.speed>c.speed)
cout<<"speed of truck is greater"<<endl;
else
cout<<"speed of car is greater"<<endl;
if(t.mileage>c.mileage)
cout<<"mileage of truck is greater"<<endl;
else
cout<<"mileage of car is greater"<<endl;

if(t.wt>c.wt)
cout<<"weight of truck is greater"<<endl;
else
cout<<"weight of car is greater"<<endl;

if(t.price>c.price)
cout<<"price of truck is greater"<<endl;
else
cout<<"price of car is greater"<<endl;
}

void main()
{
clrscr();
truck t;
car c;
cout<<"enter the data for truck"<<endl;
t.input();
cout<<"details of truck"<<endl;
t.display();
cout<<"enter the data for car"<<endl;
c.input();
cout<<"details of car"<<endl;
c.display();
cout<<"comparision is: "<<endl;
compare(t,c);
getch();
}

No comments:

Post a Comment