Tushar Garg
Tushar Garg

Reputation: 81

Error: invalid use of non-static data member in CPP

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?

Upvotes: 0

Views: 1314

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

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.

Upvotes: 4

Related Questions