Monday, February 21, 2011

Conversion between objects of Different Classes


Conversion between objects of Different Classes

The same two methods as same as conversion between basic types and user-defined types also apply to conversions between two user-defined types. That is, you can use a one-argument constructor, or you can use a conversion function. The choice depends on whether you want to put the conversion routine in the class specifier of the source object or of the destination object.

Routine in source object
When the conversion routine is in the source class, it is commonly accomplished using a conversion function. The two classes used in the next program are rectangular and polar class. The rectangular class is similar in that its objects are points in a two dimensional plane. However, it uses a rectangular coordinate system, where the location of each point is specified by x and y coordinates. Its member functions are similar to those for polar but are adapted to rectangular coordinates.
An example:
#include <math.h>
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;   }
      void display()
      {    cout<<"(" <<xco<<","<<yco<<")";     }
};

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<<")";      }
      operator rectangular()     //casting operator function
            { double x=radius * cos(angle);
               double y=radius * sin(angle);
               return rectangular(x,y);   }  //temporary object
Text Box: Output of the program
Polar Values=(10,0.785398)
Rec Values=(7.071069,7.071067)

};
void main()
{
   rectangular rec;
   polar pol(10.0,0.785398);
   rec=pol;  //or rec=rectangular(pol);
                 // It is equivalent to pol.operator rectangular()
   cout<<"\nPolar Values=";
   pol.display();
   cout<<"\nRec Values=";
   rec.display();
   }

2 comments: