The following statements are both valid:
static const A = 2;
const B = 3;
What is the difference of declaring the first or the second?
The following statements are both valid:
static const A = 2;
const B = 3;
What is the difference of declaring the first or the second?
If the static
const were to be declared inside a class it'd accesible from the class and any instance of the class, so all of the would share the same value; and the const alone will be exclusive for every instance of the class.
Given the class:
class MyClass {
public:
static const int A = 2;
const int B = 4;
};
You can do this:
int main() {
printf("%d", MyClass::A);
/* Would be the same as */
MyClass obj;
printf("%d", obj.A);
/* And this would be illegal */
printf("%d", MyClass::B);
}
Check it out here on Ideone.
Static means the entire class only shares 1 const, where non-static means every instance of the class has that const individually.
Example:
class A{
static const a;
const b;
}
//Some other place:
A m;
A n;
Objects m and n have the same a, but different b.