Problems with C ++ class / vector pointer

I am trying to use a class pointer vector. When I try to access any of the members of the Agent class, I either get a bad pointer or null data. The code is as follows.

class Grue : public Agent
{
    string name;
    Room *cur_room;
 public:
   Functions()....
};

class Agent
{
        Room *cur_room;
        string name;
  public:
         Functions()....
};


Grue* Grue1 = new Grue("Test", roompointer);
vector<Agent*> agents;
agents.push_back(Grue1);
+3
source share
1 answer

Data items are private by default in the class. Thus, the variables cur_room , name are different in the Agent and Grue classes. When you call the Grue constructor, the Grue fields are initialized, but the vector retains the agent pointers, so you get access to the agent fields that are not initialized.

here is the correct way:

class Agent
{
protected:
    Room *cur_room;
    string name;
public:
    Agent(string n, Room * r)
    : cur_room (r), name(n)         
    {}
};

class Grue : public Agent
{

public:
    Grue(string n, Room * r):Agent(n,r)
    {

    }
};
+4
source

All Articles