class armon
{
static const int maxSize=10;
int array[maxSize];
int count=0;
int* topOfStack=array;
}
Why does maxSize
need to be static
for it to be used inside array?
Basically, static is used for a constant variable or a method that is same for every instance of a class. The main method of a class is generally labeled static. In order to create a static member (block, variable, method, nested class), you need to precede its declaration with the keyword static.
What does static mean? When you declare a variable or a method as static, it belongs to the class, rather than a specific instance. This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don't create any. It will be shared by all objects.
1) Java static variable The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.
It doesn't have to be static, but it must be a constant expression.
C++ Standard § 8.3.4 [dcl.array] (emphasis mine) :
If the constant-expression (5.19) is present, it shall be a converted constant expression of type std::size_t and its value shall be greater than zero
That is, the following is also valid :
constexpr std::size_t Size() { return 10; };
struct Y
{
int array[Size()];
};
Note:
Since the compiler needs to know the size of the class, you cannot do this :
struct Y
{
const int size = 10;
int array[size];
};
Possibly making different instances of Y
having different sizes.
Also note that in this context, int array[size]
is not a constant expression, because it makes use of this
, see the C++ standard section § 5.19 [expr.const] :
A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
— this (5.1.1), except in a constexpr function or a constexpr constructor that is being evaluated as part of e;
(the evaluation of size
is really this->size
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With