-1

I want to initialize an array of stationary objects. I am taking input of number_of_stationary_items in the constructor.

The error I get is:

invalid use of non-static data member

Here is how I am doing it:

class Inventory
{
    int number_of_stationary_items;
    Stationary S1[number_of_stationary_items];

public:

    Inventory()
    {
        cout << "Enter number of stationary items: ";
        cin >> number_of_stationary_items;
    }
    

};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    Raw arrays are intended for situations where we know the size at compile time. The size of your array is `number_of_stationary_items`, which is not a compile-time constant. Use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead. – Silvio Mayolo Jul 27 '21 at 19:45
  • What you want is a `std::vector`. If this is a class assignment, and you can't use `std::vector`, then you need to create a dynamically sized array, like this post details: https://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers – NathanOliver Jul 27 '21 at 19:46

1 Answers1

1

The way to do this with the fewest changes to your code is to use std::vector.

#include <vector>
struct Stationary final {};
class Inventory
{
    int number_of_stationary_items;
    std::vector<Stationary> S1;

public:

    Inventory()
    {
        cout << "Enter number of stationary items: ";
        cin >> number_of_stationary_items;
        S1.resize(number_of_stationary_items);
    }
};

Notice the call to resize() once to know the number of items.

  • 1
    Note that with `std::vector`, there is no need for `number_of_stationary_items` to be a class member anymore, it should be a local variable of `Inventory()` instead. Any time you need to know how many items are in the `vector`, you can use its `size()` method instead. – Remy Lebeau Jul 27 '21 at 22:37