In C++ there are static and non-static const
data members.
When I want a constant, I always make it static
because it does not make sense to have multi
class MyClass
{
public:
MyClass(int val): myVal(val) {}
const int myVal;
};
In this small example, myVal
is readable by everyone without a getter method, but it's not modifiable as soon as MyClass is instantiated.
You just declare data types as const
if you want to make sure they are not modified later on.
Because myVal
is not static
, it can have different values for every different instance of MyClass
. If myVal
would be static
, it would have the same value for every instance and would not be assignable by the constructor.
Take the following example
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass(int val) : myConst(val) {}
void printVars() {
cout << "myStatic " << myStatic << endl;
cout << "myConst " << myConst << endl;
}
static const int myStatic;
const int myConst;
};
const int MyClass::myStatic = 5; //Note how this works without
//an instance of MyClass
int main()
{
MyClass ca(23);
MyClass cb(42);
cout << "ca: " << endl;
ca.printVars();
cout << "cb: " << endl;
cb.printVars();
return 0;
}
Results:
ca:
myStatic 5
myConst 23
cb:
myStatic 5
myConst 42
The following would result in a compilation error because the variables are const:
ca.myConst = 11;
ca.myStatic = 13;
static const
applies to the classconst
applies to the objectE.g.
class Verticies {
public:
const int colour;
static const int MAX_VERTICIES = 100;
Point points[MAX_VERTICIES];
Verticies(int c) : colour(c) { }
// Etc
};
Here MAX_VERTICIES
applies to all objects of type Verticies
. But different objects could have different colours and that colour is fixed on construction