jburn7
jburn7

Reputation: 125

C++ Why isn't my vector of objects printing the objects' variables?

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?

Upvotes: 0

Views: 1189

Answers (1)

Quentin
Quentin

Reputation: 63144

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.

Upvotes: 2

Related Questions