I am having a problem concerning a static const member variable I want to use to set a certain property of my class during development time. The question actually concerns proper implementation as I do have a solution that "works" at least. The variable should denote the size of a member array which I don't want to allocate on the heap due to serious performance issues. So here is my code:
1 2 3 4 5 6 7 8 9
|
//MyClass.h
class MyClass{
public:
static const int MyArraySize = 256;
private:
int MyArray[MyArraySize];
};
|
This works but it's not nice for two reasons:
1) It doesn't separate interface from implementation. I would prefer to define the variable in the corresponding .cpp file but it doesn't work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
//MyClass.h
class MyClass{
public:
static const int MyArraySize;
static const int MyValue;
private:
int MyArray[MyArraySize];
};
//MyClass.cpp
#include "MyClass.h"
const int MyClass::MyArraySize = 256;
const int MyClass::MyValue = 100;
|
If I delete the line
int MyArray[MyArraySize];
the above code works but when I use it to define the size of the array I get a "constant expression expected" error for the line
int MyArray[MyArraySize];
which makes sense as the compiler does not know the value of MyArraySize when he reaches
int MyArray[MyArraySize];
and therefore can not allocate the memory. Of course I can move MyArray to the heap like that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
//MyClass.h
class MyClass{
public:
static const int MyArraySize;
static const int MyValue;
MyClass();
~MyClass();
private:
int* MyArray;
};
//MyClass.cpp
#include "MyClass.h"
const int MyClass::MyArraySize = 256;
const int MyClass::MyValue = 100;
MyClass::MyClass(){
MyArray = new int(MyArraySize);
}
MyClass::~MyClass(){
delete[] MyArray;
}
|
But as I mentioned before this causes a remarkable loss of performance.
2)
Something like the following does not work:
1 2 3 4 5 6 7 8 9
|
//MyClass.h
class MyClass{
public:
static const int MyArraySize = (int) pow(2, 8);
private:
int MyArray[MyArraySize];
};
|
This gives a "constant expression expected" error for the line
static const int MyArraySize = (int) pow(2, 8);
Interestingly the following code works:
1 2 3 4 5 6 7 8 9 10 11
|
//MyClass.h
class MyClass{
public:
static const int MyValue;
};
//MyClass.cpp
#include "MyClass.h"
const int MyClass::MyValue = (int) pow(2, 8);
|
So if I use pow outside of the class definition I get no errors. Is there any solution to those problems? So what I want is:
1) Don't allocate the array on the heap
2) Separate interface from implementation
3) Being able to use functions like pow to define MyArraySize
4) Not use global variables
Thanks in advance for any help!