Previous Section  < Free Open Study >  Next Section

Correct Method for Leak #7


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

};



void

Point::print()

{

 cout << ''I live at ('';

 cout <<x<<'', ''<<y<<'') and'';

 cout << ''I'm'' << str(color) <<''.\n'';

}



const Point

Point::operator+(const Point& rhs)

{

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

}



main()

{

 Point p1(10, 10, ''Blue'');

 Point p2(20, 60, ''Green'');

 Point p3 = p1 + p2;



 p3.print();

}

    Previous Section  < Free Open Study >  Next Section