0

I am new to C++ and I am trying to do the following:

class abc {
    public:
    int no_of_consumer;
    struct def {
        int p = 0;
        int c = 0;
    };
    def variable[no_of_consumer - 1];
};

int main() {
    abc obj1;
    obj1.no_of_consumer = 1;
};

I want the variable no_of_consumer to be set by the main() function, so that I can use this variable to define a structure array for variable def. But I am getting this error:

invalid use of non-static data member "no_of_consumer".

Am I missing some concept here?

4
  • 5
    c++ does not support VLAs. no_of_consumer must be a compile time constant. Use std::vector for dynamically sized arrays.
    – drescherjm
    Commented Jan 29, 2018 at 15:08
  • 1
    Please always post the whole error, including the line/column number the compiler gave you. Commented Jan 29, 2018 at 15:09
  • 2
    In c++, assigning to a variable is not retroactive. Even if you could create an array data member with a sized determined by non-const like that, changing that variable could not retroactively resize the array. Commented Jan 29, 2018 at 15:10
  • 1
    OT: no_of_consumer - 1 why -1?
    – user2672107
    Commented Jan 29, 2018 at 15:13

1 Answer 1

4

The problem lies here:

def variable[no_of_consumer - 1];
             ^^^^^^^^^^^^^^^^^^

In C++, array sizes must be constant expressions. If you want to have a dynamically sized array, use std::vector instead.

Note that you'll also need custom logic to resize your vector; as mentioned in the comments, you can't make that automatically depend on the value of your variable.

4
  • can you help me for this example. How should I use std::vector ? Commented Jan 29, 2018 at 15:14
  • @TusharGarg Stack Overflow is not a tutorial service. Asking "How should I use std::vector" would be far too broad a question. Consider searching the internet for examples. Standard container templates are fundamental part of c++ and there are plenty of resources online to learn about them. Commented Jan 29, 2018 at 15:19
  • 1
    I tried using: std::vector<def> variable[no_of_consumer - 1]. But I am still getting the same error. Commented Jan 29, 2018 at 15:33
  • 1
    @TusharGarg that's expected, because you used vector in a wrong way. A good C++ book will explain how to use it. Commented Jan 30, 2018 at 8:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.