Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid use of non-static data member while using const variable

Tags:

c++

class Try {
    const int no = 5;
    int arr[no];
};

Here is a simple class , but I get this compilation error. no is constant so I thought it should not be the problem.

like image 856
Abhishek Garg Avatar asked Dec 18 '22 18:12

Abhishek Garg


1 Answers

arr must have the same size in all instances of your class. no is const but that only means it never changes after an instance is created. It doesn't mean that it is the same for all instances all the time. For example, no can be set in the initializer list of the constructor

Foo::Foo(int size) : no(size)
{}

For this reason, unless you make no static, you can't use it as array size because that would imply potentially differently sized arrays in each instance.

like image 94
Nikola Dimitroff Avatar answered May 24 '23 01:05

Nikola Dimitroff