Question

Been banging my head against a brick wall for sometime with this problem. Was hoping I may be able to get some help here.

Basically, my game has an inventory system with a number of different objects. There are different classes derived from the base class Object and they use virtual functions in order to have different behaviour with the same function call.

Originally, I had a list inventory as well as a list::iterator invIter. The iterator would call the functions I needed for the right object in the inventory but would only call base class functions. I read from another answer that the reason for this is because you lose the polymorphic nature when you do this but having a list of pointers would remedy it.

So I changed the list and iterator so they were Object pointers and found out the supposedly correct way to access the functions and variables of the inventory objects. However, when these functions or variables get accessed at runtime, the program has an unhandled exception and breaks.

This is my code which causes the issue....

Header

#include "Object.h"
#include <vector>
#include <list>

using namespace std;

class Player
{
public:
    Player();

    void addItem(Object);
    void printInventory();

    list<Object*> inventory;

private:    
    list<Object*>::iterator invIter;       
};

cpp

#include "Player.h"
#include "Object.h"

#include <iostream>



Player::Player()
{

}

void Player::addItem(Object newItem)
{
    inventory.push_back(&newItem);
    return;
}


void Player::printInventory()
{
    cout << "YOU ARE CARRYING: \n";
    for(invIter=inventory.begin(); invIter!=inventory.end(); ++invIter)
    {       

        cout << (*invIter)->getName() << ", ";

    }

    cout << "\nPRESS RETURN TO CONTINUE...";
    cin.ignore(1);
    return;
}

Any help is much appreciated, I've honestly hit a dead end myself.

Was it helpful?

Solution

The problem is in your addItem method:

void Player::addItem(Object newItem)
{
    inventory.push_back(&newItem);
    return;
}

Here, you're passing newItem by value. This means that newItem, as a function parameter, is effectively a local variable, holding a copy of the object passed to it. You then take a pointer to this local variable and store it for later use, but it goes out of scope at the end of the function. At this point the pointer is no longer valid.

To fix this, you should pass newItem by reference: preferably as an actual reference (Object&) but passing a pointer to it would work too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top