Hi guys,
I've got a class that has a member variable which is a pointer to an object of the same class. I'm having problems dealing with some of the constructors (mainly copy) and assignment operator. I don't think I've ever written classes with this special case, although I realize it shouldn't be too hard. If you have any ideas on how to best rewrite my copy construct, assignment operator, or anything else (trivial constructors??), please let me know!
Thanks, Andrew
Code:Location.h #ifndef LOCATION_H #define LOCATION_H using namespace std; class Location { private: int row, col, cost; Location* history; public: Location() { row = col = cost = 0; history = NULL; } Location(int r, int c) { row = r; col = c; cost = 0; history = NULL; } Location(const Location& loc); ~Location() { delete history; history = NULL; } int getRow() const { return row; } int getCol() const { return col; } int getCost() const { return cost; } void setCost(int c) { cost = c; } void setHistory(Location loc) { *history = loc; } Location& getHistory() const { return *history; } bool operator < (const Location& loc) const { return (cost > loc.getCost()); } Location& operator =(const Location& loc); }; #endif Location.cpp #include"location.h" using namespace std; Location::Location(const Location& loc) { if (loc.history != NULL) { row = loc.row; col = loc.col; cost = loc.cost; } history = new Location(); *history = loc.getHistory(); } Location& Location::operator =(const Location& loc) { if (this != &loc) { row = loc.row; col = loc.col; cost = loc.cost; if (history != NULL) delete history; history = new Location(loc.getHistory()); } return *this; }