'How to access a vector from another class?

I am working on a car rental program, and in it I need to be able to access a vector of the cars and prices from another class in order to make the receipt. Except every time I try to access the vector, there is nothing in it. How can I access the vector with the data in it?

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
const string SPORTS_CARS = "sports.dat";
class InventoryItem
{
public: 
  InventoryItem() {};
  ~InventoryItem() {};
  friend class Cart;
  vector<string> listOfCars;
  vector<float> listOfPrices;
  void readSports()
  {
    string car;
    float price;
    ifstream input(SPORTS_CARS);
    if (input.is_open())
    {
      while (!input.eof())
      {
        getline(input, car);
        input >> price;
        input.ignore();
        listOfCars.push_back(car);
        listOfPrices.push_back(price);
      }
    input.close();
  }
  }
};

class Cart
{
public:
  Cart() {};
  ~Cart() {};
  void select()
  {
    InventoryItem a;
    for (int i = 0; i < a.listOfCars.size(); i++)
    {
      cout << a.listOfCars[i] << endl;
    }
  }
};

int main() {
  InventoryItem item;
  item.readSports();
  Cart cart;
  cart.select();
}


Solution 1:[1]

The problem is that you create an empty 'Inventory' and then try to read it

InventoryItem a;  <<<<==== empty
string carName;
cout << "What car do you want: ";
getline(cin >> ws, carName);
for (int i = 0; i < a.listOfCars.size(); i++) <<<====

You need to somehow have an 'loaded' Inventory and pass it as a parameter to this function. Or have the Cart constructor take an Inventory as an argument.

Its hard to propose an exact solution without seeing the whole code base.

OK now that you have made a good minmal example - heres how to fix it

  void select(InventoryItem &inv)
  {
    for (int i = 0; i < inv.listOfCars.size(); i++)
    {
      cout << inv.listOfCars[i] << endl;
    }
  }

and in main

cart.select(item);

Maybe this is just an English language thing , but calling the inventory 'InventoryItem' is odd. 'InventoryItem' suggests one thing thats in the inventory. I would expect to see an 'Inventory' class that contains 'InvertoryItem's - of maybe just 'Car' objects

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1