#include <iostream>
#include <memory>
using namespace std;
class myException
{
public:
char * errorMsg() { return "Oops."; }
};
class Point
{
public:
Point (int x, int y):myX(x), myY(y) { cout << "Point constructor called"<< endl;}
Point (const Point & rhs):
myX(rhs.myX),
myY(rhs.myY){ cout << "Point copy constructor called" << endl;}
~Point(){ cout << "Point destructor called" << endl;}
int GetX() const { return myX; }
void SetX(int x) { myX = x; }
int GetY() const { return myY; }
void SetY(int y) { myY = y; }
private:
int myX;
int myY;
};
class Rectangle
{
public:
Rectangle( Point upperLeft, Point lowerRight ):
myUpperLeft(new Point(upperLeft)),
myLowerRight(new Point(lowerRight))
{}
Rectangle( auto_ptr<Point> pUpperLeft, auto_ptr<Point> pLowerRight ):
myUpperLeft (new Point(*pUpperLeft)),
myLowerRight(new Point(*pLowerRight))
{}
Rectangle( int upperLeftX, int upperLeftY, int lowerRightX, int lowerRightY ):
myUpperLeft(new Point(upperLeftX,upperLeftY)),
myLowerRight(new Point(lowerRightX,lowerRightY))
{}
Rectangle( const Rectangle & rhs ):
myUpperLeft(new Point(*myUpperLeft)),
myLowerRight(new Point(*myLowerRight))
{}
~Rectangle(){ cout << "In Rectangle's destructor" << endl; }
int GetWidth() { return myLowerRight->GetX() - myUpperLeft->GetX(); }
int GetHeight() { return myLowerRight->GetY() - myUpperLeft->GetY(); }
void DangerousMethod() { throw myException(); }
private:
auto_ptr<Point> myUpperLeft;
auto_ptr<Point> myLowerRight;
};
int main()
{
try
{
cout << "Begin round 1..." << endl;
auto_ptr<Point> pUL(new Point(0,0));
auto_ptr<Point> newAutoPtr = pUL;
auto_ptr<Point> pLR(new Point(20,30));
Rectangle myRectangle(pUL, pLR);
int w = myRectangle.GetWidth();
int h = myRectangle.GetHeight();
cout << "the Rectangle is " << w << " by " << h << endl;
}
catch ( myException & e )
{
cout << "caught exception: " << e.errorMsg() << "\n\n" << endl;
}
try
{
cout << "Begin round 2..." << endl;
auto_ptr<Point> pUL(new Point(0,0));
auto_ptr<Point> pLR(new Point(20,30));
Rectangle myRectangle(pUL, pLR);
int w = myRectangle.GetWidth();
int h = myRectangle.GetHeight();
cout << "the Rectangle is " << w << " by " << h << endl;
myRectangle.DangerousMethod();
}
catch ( myException & e )
{
cout << "caught exception: " << e.errorMsg() << "\n\n" << endl;
}
return 0;
}