Reputation: 47
At a loss here hope someone can help..
I have the following class structure.
A base class Room with two child classes Kitchen
, and livingRoom
.
I have a vector in my base class
Room::Room()
{
up = nullptr;
down = nullptr;
left = nullptr;
right = nullptr;
pocket = new vector<string>;
}
Defined as:
void Room::addPocket(string item)
{
char emptyPocket;
if (pocket->size()==1)
{
emptyPocket = 'N';
}
if(pocket->size()<1)
{
pocket->push_back(item);
cout << "Item added to pocket" << endl;
}
else
{
cout <<"Your pocket is full" << endl;
cout <<"Would you like to empty your pocket? 'Y' or 'N'" << endl;
cin >> emptyPocket;
if(emptyPocket == 'Y' || emptyPocket == 'y')
{
pocket->clear();
cout <<"You have emptied your pocket." << endl;
}
}
}
And my program function as follows. I have a another class Game
, where the following happens. I go into the child
class Kitchen
and add to the vector. Go back into Game
class. I move into the livingRoom
class and when I access the vector, is empty? What am I missing here ?
Upvotes: 0
Views: 87
Reputation: 33952
Base class data is not shared between different instances of child classes. Each child class is, and effectively contains, a distinct instance of the base class.
So Kitchen
has a pocket
and livingRoom
has another pocket
. What is added to Kitchen
's pocket
is not added to LivingRoom
's pocket.
Instead, you should look into making another class to represent the entity that is moving between the rooms and have this entity class contain pocket
. No matter what room an entity is in, it always has the same pocket
.
Also shy away from dynamically allocating std::vector
s. They were designed to take away all of the responsibilities of managing dynamic allocations, so dynamically allocating a vector
merely puts some of the those management responsibilities back into play for no benefit.
Upvotes: 1