Monday, February 21, 2011

Routine in destination object


Routine in destination object
When the conversion routine is in the destination class, we use a one-argument constructor. However, things are complicated by the fact that the constructor in the destination class must be able to access the data in source class to perform the conversion. The polar data – radius & angle –are private, so we must provide special function to allow direct access it.

#include<iostream.h>
#include<conio.h>
#include <math.h>
class polar
{
      double radius,angle;          //x and y cordinate
   public:
      polar()        //constructor
      { radius=0.0;
            angle=0.0; }

    polar(double r, double a)
      {   radius=r; angle=a;   }

   void display()
   { cout<<"(" <<radius<<","<<angle<<")"; }

      double getr()
      {  return radius;   }

      double geta()
      {   return angle;   }
};

class rectangular
{
      double xco,yco;          //x and y cordinate
   public:
      rectangular()          //constructor
      {   xco=0.0; yco=0.0;   }

      rectangular(double x, double y)
      {   xco=x; yco=y;   }

      rectangular (polar p)
      {
             double r=p.getr();
             double a=p.geta();
             xco=r * cos(a);
             yco=a * sin(a);
      }

      void display()
      {    cout<<"(" <<xco<<","<<yco<<")";  }
};

void main()
{
   rectangular rec;         //rectangular using constructor1
   polar pol(10.0,0.785398);     //polar using constructor1
   rec=pol;        //convert polar to rectangular using conversion function
   clrscr();
Text Box: Output of the program
Polar Values=(10,0.785398)
Rec Values=(7.071069,0.55536)


   cout<<"\nPolar Values=";
   pol.display();
   cout<<"\nrectangular Values=";
   rec.display();
   getch();
}

No comments:

Post a Comment