Write a C++ program to create two classes Class1 and Class2. Each class contains one float data member. Write following functions: i. To accept float numbers ii. To display float numbers in right justified format with precision of two digits iii. To Exchange the private values of both these classes by using Friend function.

//Note: If you are not using Borland or Turbo C then add the following line after header files :
//using namespace std;

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class c2;
class c1
{
   private:
   float f1;
   public:
   void accept()
   {
    cout<<"\nEnter float number(in class 1): ";
      cin>>f1;
   }
   void disp()
   {
       cout.right;
       cout.precision(2);
       cout<<"\nFloat no is: "<<f1;
   }
   void friend change(c1 p,c2 r); //friend function declared
};
class c2
{
   private:
   float f2;
   public:
   void accept()
   {  cout<<"\nEnter float number(in class2 ): ";
      cin>>f2;
   }
   void disp()
   {
       cout<<"\nFloat no is: "<<f2;
   }
     void friend change(c1 p,c2 r); //friend function declared
};
void change(c1 p,c2 r)
  {
      float temp;
      temp=p.f1;
      p.f1=r.f2;
      r.f2=temp;

      cout<<"\nAfter changing values: \n"<<"in class 1 : "<<p.f1<<"\nin class 1 : "<<r.f2;
  }
int main()
{
   int n;
   c1 c; //object created
   c2 p; //object created
   do{
   cout<<"\n1.Accept float numbers\n2.display float numbers in right justified format\n3.Exchange the private values\n4.Exit\nEnter your choice :- ";
   cin>>n;
switch(n)
   {
   case 1:c.accept();
  p.accept();break;
   case 2:c.disp();
  p.disp();break;
   case 3:change(c,p);break;
   }
   }while(n!=4);
}

0 Comments