-
Forward Declaration
I swear I've done this a hundred times before, but, I need a member function that returns an object of the type of class that I'm creating. I though I fixed this problem in the past with forward declaration, but things aren't working (compiling) right now. Perhaps you can shed some light. Here is my code:
Code:
#ifndef LOCATION_H
#define LOCATION_H
#include<vector>
using namespace std;
class Location; // Forward Declaration
class Location
{
private:
int row, col, cost;
Location history; // This is the problem line
public:
Location()
{ row = col = 0; }
Location(int r, int c)
{ row = r; col = c; }
int getRow()
{ return row; }
int getCol()
{ return col; }
int getCost() const
{ return cost; }
void setCost(int c)
{ cost = c; }
void setHistory(Location loc)
{ history = loc; }
Location getHistory()
{ return history; }
bool operator < (const Location& loc) const
{ return (cost > loc.getCost()); }
};
#endif
Andrew
-
Think about that... when an object of location is constructed, its member variable location is construted, and the member variables member variable is constructed... etc etc.
The only way this would make sense is for history to be a pointer
Location *history;
-
In a previous version of the code, I had used a vector<Location> for history, but eventually realized I only needed one history element. Why did the vector work?
Andrew
-
Because no Location objects are constructed until you call vector::<T>push_back() or vector<T>::resize() or a similar function
-
Yeah, I spose that makes sense. Thanks, I'll use history as a Location*