C++ Accessing a list of Pointers to Objects members, through an iterator -


been banging head against brick wall sometime problem. hoping may able here.

basically, game has inventory system number of different objects. there different classes derived base class object , use virtual functions in order have different behaviour same function call.

originally, had list inventory list::iterator inviter. iterator call functions needed right object in inventory call base class functions. read answer reason because lose polymorphic nature when having list of pointers remedy it.

so changed list , iterator object pointers , found out supposedly correct way access functions , variables of inventory objects. however, when these functions or variables accessed @ runtime, program has unhandled exception , breaks.

this code causes 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 carrying: \n";     for(inviter=inventory.begin(); inviter!=inventory.end(); ++inviter)     {                 cout << (*inviter)->getname() << ", ";      }      cout << "\npress return continue...";     cin.ignore(1);     return; } 

any appreciated, i've hit dead end myself.

the problem in additem method:

void player::additem(object newitem) {     inventory.push_back(&newitem);     return; } 

here, you're passing newitem by value. means newitem, function parameter, local variable, holding copy of object passed it. take pointer local variable , store later use, goes out of scope @ end of function. @ point pointer no longer valid.

to fix this, should pass newitem reference: preferably actual reference (object&) passing pointer work too.


Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -