0

I have a class called "Region", and I have a class called "Map". The "Map" class has a vector of type "Region *" called "regions" as a member. In the .cpp file for the "Map" class, I have a "getRegions" function that returns this "regions" vector.

In main.cpp, I initialize a "Region *", called "australia", and then try to use the "getRegions" function to call the "push_back" function for the vector. I've never had problems with using "push_back" before, but when I test to see if this "Region *" is actually in the "regions" vector, it always comes back as empty.

CLion compiles and runs the program without any errors. Is it wrong to call the "push_back" function in conjunction with a "get" function?

Here is the driver code.

int main() {
    Map map;
    Region *australia;

    map.getRegions().push_back(australia);

    if (map.getRegions().empty()) {
        std::cout << "Empty"; //always prints this for some reason, even though I just pushed it back
    } else {
        std::cout << "Not Empty";
    }

    return 0;
}
wolfeweeks
  • 355
  • 4
  • 12
  • 3
    Please post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). My guess is `getRegions` is *not* returning by reference. – cigien May 22 '20 at 16:18
  • `map.getRegions().push_back(australia);` -- This code cannot be correct, since you are adding an uninitialized pointer to the vector. – PaulMcKenzie May 22 '20 at 16:42

2 Answers2

1

Without seeing all your code it's difficult to tell, but based on your shown code, and described behavior, my guess is that your function looks something like:

auto Map::getRegions() -> std::vector<Region>
{
  // ...
  return regions;
}

This would mean you are making a copy of the vector, and you are push_backing onto a copy.

Instead, you need to write it like:

auto Map::getRegions() -> std::vector<Region> &
{
  // ...
  return regions;
}

so that you return a reference to the regions member.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • It was originally this: `std::vector Map::getRegions() { return regions; }` But now I added the ampersand: `std::vector &Map::getRegions() { return regions; }` – wolfeweeks May 22 '20 at 16:29
  • hmm, ok, but consider not using pointers at all. They are a source of bugs, so avoid them unless necessary. – cigien May 22 '20 at 16:33
0

Read up on the concept of pass-by-value, pass-by-reference, and pass-by-pointer. Your function getRegions is probably returning the member by value, meaning, you are creating a temporary copy, and adding australia to the copy, not the actual member.

BTownTKD
  • 7,911
  • 2
  • 31
  • 47