Reputation: 1976
Suppose I have:
class Map {
public:
Map();
vector<Territory>* getTerritories();
};
vector<Territory>* Map::getTerritories()
{
vector<Territory> t;
for (int i = 0; i < 8; i++) {
Territory ter;
ter.setName("Territory " + std::to_string(i + 1));
t.push_back(ter);
}
return &t;
}
Now in another class, I want to get the same vector I created in the getTerritories()
method.
Here's how:
void GameSetup::assignTerritories()
{
vector<Territory> * generatedTeritories = (*map).getTerritories(); // dereferenced
}
I'm not getting a compiler error because they're both pointers. But somehow I cannot seem to access my Territory objects within my vector by simple iteration like you would normally do over a vector.
At this point, (*map).getTerritories()
gets a pointer to my territory vector (if I try to follow). Now suppose I want to make an 'alias' of some sort of this pointer I'm returning, how would I do so? Is it possible to get the address of a pointer? I asked myself this question and tried the following:
vector<Territory> * generatedTeritories = &(map->getTerritories());
but that obviously didn't work. I'm not sure what else to do and I've been going in circles.
Upvotes: 0
Views: 45
Reputation: 21604
Please, forget pointers here. getTerritories()
was returning a pointer to a local object. This object is destroyed after the function return. You just need to return the object and you'll then find in back in your generatedTeritories
variable.
class Map {
public:
Map();
vector<Territory> getTerritories();
};
vector<Territory> Map::getTerritories()
{
vector<Territory> t;
for (int i = 0; i < 8; i++) {
Territory ter;
ter.setName("Territory " + std::to_string(i + 1));
t.push_back(ter);
}
return t;
}
void GameSetup::assignTerritories()
{
vector<Territory> generatedTeritories = (*map).getTerritories(); // dereferenced
}
Now you can get the address of the vector like that:
vector<Territory>* addressOfGeneratedTeritories = &generatedTeritories;
But it's only safe to use it while generatedTeritories
remains alive (in the code above, it's alive untill assignTerritories()
execution ends as it is a local variable of this function). To make it persistent, it has to be an attribute of another object...it will then remain alive untill the parent object gets destroyed...and so on. It could allso be a global variable which is definitely not recommended (it's a bad practice, object oriented design always have alternatives to that).
BTW, I would recommend that you follow some tutorials about C++ before starting to code a game.....;-)
Upvotes: 1