Previous Section  < Free Open Study >  Next Section

Returning an Internal Static Object Reference

#include <iostream.h> 

class Point {

 int x, y;

 char* color;


 Point(int = 0, int = 0, char* = ''Red'');


 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);



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.

    Previous Section  < Free Open Study >  Next Section