Using a pointer as a return value.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sampandaran
    New Member
    • Nov 2006
    • 2

    Using a pointer as a return value.

    Hey, I'm having some trouble with a program I'm trying to write and was hoping someone here could help me. Basically I have a dynamic 2D array of the 'Square' class and in the square class is the pointer 'item.' 'item' is a pointer of another class that I have called 'Inhabitant' and I have 3 derived classes off of 'Inhabitant.' I need to somehow have a pointer function in 'square' that returns the pointer 'item.'

    From the header file for the square class:
    class Square
    {
    public:
    Square();
    Square(Inhabita nt* anItem);
    ~Square();
    Inhabitant* getInhabitant() const; /* This is what I need my main to call and get a pointer passed back */
    void setInhabitant(I nhabitant* anItem);
    void removeInhabitan t();

    private:
    Inhabitant* item; /* This is the pointer that I need to have returned */
    };

    From the cpp file:
    Square::Square( )
    {
    item = NULL;
    }
    Square::Square( Inhabitant* anItem)
    {
    item = anItem;
    }
    Square::~Square ()
    {
    delete item;
    }

    Inhabitant* Square::getInha bitant() const
    {
    return item; /* This isn't working */
    }
    void Square::setInha bitant(Inhabita nt* anItem)
    {
    item = anItem;
    }
    void Square::removeI nhabitant()
    {
    item = NULL;
    }

    I don't get an error while compiling but rather when running the program I get:
    Unhandled exception at 0x00419e66 in game.exe: 0xC0000005: Access violation reading location 0xfdfdfdfd.

    If anyone could help it would be greatly appreciated. Please note that I am being forced to have the program set up this way so I can't use vectors instead of my dynamic 2D array ect.
  • dtimes6
    New Member
    • Oct 2006
    • 73

    #2
    It is really hard to get informations from ur code.
    I suggest u do the followings;

    1. write some assert(item);
    2. provide u own copy constructor and copy operator.(put them into private if u do not want them.)
    3. make sure the pointer u passed into is never deleted by this class if u delete them else where.

    Comment

    • sampandaran
      New Member
      • Nov 2006
      • 2

      #3
      I'll try those, but as it looks there is nothing wrong with returning a pointer from a function? Because I'm lost trying to figure out where the problem lies.

      Comment

      Working...