Example Code for Leak #5
#include <iostream.h>
class Point {
int x, y;
char* color;
public:
Point(int, int,char*);
// Note the commented-out copy constructor.
//Point(const Point&);
~ Point();
Point duplicate(Point);
void print();
};
Point::Point(int new_x, int new_y, char* col)
{
x = new_x; y = new_y;
color = new char[strlen(col)+1];
strcpy(color, col);
}
// This is an example copy constructor for the
// Point class. Note that it is commented out
// of the application.
/*
Point::Point(const Point& rhs)
{
x = rhs.x; y = rhs.y;
color = new char[strlen(rhs.color)+1];
strcpy(copy, rhs.color);
}
*/
Point::~Point()
}
delete color;
}
// This function takes a Point object as an
// argument ''by value. '' That will cause an
// implicit call to the copy constructor.
// In addition, the C++ statement
// ''return(*this); '' will cause an implicit call to
// the copy constructor because
// the function returns a Point
// object by value.
Point
Point::duplicate(Point rhs)
{
x = rhs.x;
y = rhs.y;
return(*this);
}
void
Point::print()
{
cout << ''I'm a point at ('';
<<x<<'' , '' <<y<< '') \n'';
cout << ''My color is''; <<color<< ''. \n\n'';
}
main()
{
Point p1(10, 10, ''Blue'');
Point p2 (15, 18, ''Green'');
// The following declaration causes an
// implicit call to the copy constructor;
Point p3 = p2;
// Another way of writing the above
// declaration is:
// Point p3(p2);
p1.print();
p2.print();
p3.print();
// The function ''duplicate'' takes a Point
// object by value and returns a local copy by
// value. The statement causes two implicit
// calls to the copy constructor.
p1.duplicate(p2);
p1.print();
p2.print();
p3.print();
}
|