0

I'm filling std::vector<Box> boxes with 9 Box objects, each with their own string variable name. Just as an error check, I'm trying to go through the vector of objects and print each object's name variable. However, the console remains blank. Here's the function that fills and prints the vector:

void Engine::FillVector(){
Board board;
for(int i = 0; i < 9; i++){
    Box box;
    board.GetBoxes().push_back(box);
    }
int size = board.GetBoxes().size();
for(int i = 0; i < size; i++){
    board.GetBoxes()[i].SetName("box");
    std::cout << board.GetBoxes()[i].GetName();
    }
}

So "box" should be displayed nine times in the console right? GetBoxes simply returns the vector boxes, and SetName also simply sets each Box object's name to "box". Why does the console remain blank?

jburn7
  • 125
  • 2
  • 3
  • 15
  • What does `Board::GetBoxes()` look like? – juanchopanza Aug 28 '14 at 13:32
  • 5
    I bet two leek slices that `GetBoxes` returns by value. – Quentin Aug 28 '14 at 13:33
  • `std::vector Board::GetBoxes(){return boxes; }` – jburn7 Aug 28 '14 at 13:33
  • Return a reference (or a pointer), otherwise your modifications won't appear in 'boxes'. – glezmen Aug 28 '14 at 13:34
  • Leek slices this way, thanks. – Quentin Aug 28 '14 at 13:34
  • I'm rusty on references/pointers. Can I get an example for this problem? And @Quentin: [link](http://www.leekspin.com) – jburn7 Aug 28 '14 at 13:36
  • You just defined Box box; without allocating it memory. You need to allocate your variable box memory: simply, box = new Box(); this will create an object instance of the class Box. – Juniar Aug 28 '14 at 13:54
  • Your board.GetBoxes() function, should return a pointer to your vector. However we do not know if you used a pointer as an array of your data structure. Usually, to make a references to the Box instance in a vector, you need to use ".at(i)" function and maybe something like board.GetBoxes().at(i); It appears, however that you are using an array index to make a reference to objects inside a vector. – Juniar Aug 28 '14 at 15:20

1 Answers1

2
std::vector<Box> Board::GetBoxes(){return boxes; }

This returns a copy of your boxes every time you call it.

std::vector<Box> &Board::GetBoxes(){return boxes; }
//               ^ Hi!

This returns a reference to your vector. You can then act on it from the outside at will.

It's often best complemented with a const overload :

std::vector<Box> const &Board::GetBoxes() const {return boxes; }

...for read-only access.

For more information about references, I will shamelessly link you to another answer of mine.

Community
  • 1
  • 1
Quentin
  • 62,093
  • 7
  • 131
  • 191