Thread: Forward Declaration

  1. #1
    Registered User
    Join Date
    Apr 2002

    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:

    #ifndef LOCATION_H
    #define LOCATION_H
    using namespace std;
    class Location; // Forward Declaration
    class Location
        int row, col, cost;
        Location history; // This is the problem line
        { 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()); }

  2. #2
    I lurk
    Join Date
    Aug 2002
    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;

  3. #3
    Registered User
    Join Date
    Apr 2002
    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?


  4. #4
    I lurk
    Join Date
    Aug 2002
    Because no Location objects are constructed until you call vector::<T>push_back() or vector<T>::resize() or a similar function

  5. #5
    Registered User
    Join Date
    Apr 2002
    Yeah, I spose that makes sense. Thanks, I'll use history as a Location*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do you resolve this error?
    By -EquinoX- in forum C Programming
    Replies: 32
    Last Post: 11-05-2008, 04:35 PM
  2. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  3. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  4. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM