In C++, is there any reason to not access static member variables through a class instance? I know Java frowns on this and was wondering if it matters in C++. Example:
class Foo {
static const int ZERO = 0;
static const int ONE = 1;
...
};
void bar(const Foo& inst) {
// is this ok?
int val1 = inst.ZERO;
// or should I prefer:
int val2 = Foo::ZERO
...
};
I have a bonus second question. If I declare a static double, I have to define it somewhere and that definition has to repeat the type. Why does the type have to be repeated?
For example:
In a header:
class Foo {
static const double d;
};
In a source file:
const double Foo::d = 42;
Why do I have to repeat the “const double” part in my cpp file?
For the first question, aside from the matter of style (it makes it obvious it’s a class variable and has no associated object), Fred Larsen, in comments to the question, makes reference to previous question. Read Adam Rosenthal’s answer for very good reason why you want to be careful with this. (I’d up-vote Fred if he’d posted it as answer, but I can’t so credit where it’s due. I did up-vote Adam.)
As to your second question:
You have to repeat the type primarily as an implementation detail: it’s how the C++ compiler parses a declaration. This isn’t strictly ideal for local variables either, and C++1x (formerly C++0x) makes use of the
autokeyword to avoid needing to be repetitive for regular function variables.So this:
can become this:
There’s no clear reason why this couldn’t work with static as well, so in your case thos:
could well become this.
The key is to have some way of identifying this as a declaration.
Note I say no clear reason: C++’s grammar is a living legend: it is extremely hard to cover all of its edge cases. I don’t think the above is ambiguous but it might be. If it isn’t they could add that to the language. Tell them about it … for C++2x :/.