Returning an Internal Static Object Reference

 <  Free Open Study  >  

 #include <iostream.h>  class Point {  int x, y;  char* color; public:  Point(int = 0, int = 0, char* = ''Red'');  ~Point();  Point(const Point&);  void print();  const Point& operator=(const Point&);  const Point& operator+(const Point&); }; const Point& Point::operator+(const Point& rhs) { // Note the use of the internal static storage class // for temp. Each caller to this function reads and // writes exactly the same Point object.  static Point temp;  temp.x = x + rhs.x; temp.y = y + rhs.y;  delete temp.color; //Not exactly a good color-mixing scheme!  temp.color = new char[strlen(color)+strlen(rhs.color)+1];  sprintf(temp.color, ''%s%s'', color, rhs.color);  return(temp); } 

Taking a step back to examine the relevant problems of each example, we realize that we need a completely separate Point object upon each invocation of the operator, yet its existence must include the scope of the operator's return value. The logical choice is to dynamically allocate the new Point object from within the overloaded operator and to return a Point reference to it.

 <  Free Open Study  >  


Object-Oriented Design Heuristics
Object-Oriented Design Heuristics (paperback)
ISBN: 0321774965
EAN: 2147483647
Year: 1996
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net