I was experimenting with static keyword in c++. The following class has a static variable called size which is initialized as 10.
class staticTest
{
public:
static int size;
int x,y;
staticTest()
{
x=0;
y=0;
}
void display()
{
printf("%d %d\n",x,y);
}
};
int staticTest::size=10;
Now i have another class which uses this static variable. Here is the other class
class my
{
public:
int a[staticTest::size];
my()
{
for(int i=0;i<staticTest::size;i++)
{
a[i]=i;
}
}
void display()
{
for(int i=0;i<staticTest::size;i++)
{
printf("%d\n",a[i]);
}
}
};
Now i have main function like this
main()
{
my ni;
ni.display();
}
I am unable to compile this program. Error is that array bound is not an integer constant. Why is this so?
Only compile-time constants can be used as array sizes.
Declare your integer as
static const int.Also, the (default) value needs to go in the declaration, not the definition:
Based on your comment, consider this: At the moment, you are effectively using a global variable to communicate some dynamic quantity. This should ring alarm bells:
This is terrible design, for a whole range of reasons. Instead, you should make the relevant size part of the class:
Now you can communicate the desired size locally: