The definition of a variable in C++11 is as follows (§3/6):
A variable is introduced by the declaration of a reference other than a non-static data member or of an object. The variable’s name denotes the reference or object.
So a non-static data member reference is not a variable. Why is this distinction necessary? What's the rationale here?
Here's one way I can declare a variable in C++:
int scientist = 7;
After this declaration (and definition, in this case), I can use scientist
to read and set its value, take its address, etc. Here's another kind of declaration:-
class Cloud {
public:
static int cumulonimbus = -1;
};
This one is a bit more complicated, because I have to refer to the new variable as Cloud::cumulonimbus
, but I can still read and set its value, so it's still obviously a variable. Here's a yet different kind of declaration:-
class Chamber {
public:
int pot;
};
But after this declaration, there isn't a variable called pot
, or Chamber::pot
. In fact there's no new variable at all. I've declared a new class, and when I later declare an instance of that class it will have a member called pot
, but right now, nothing is called that.
A non-static data member of class doesn't create a new variable itself, it just helps you to define the properties of the class. If it did create a new variable, you'd be able to write code like this:
class Chamber {
public:
int pot;
};
void f(bool b) {
if (b)
Chamber::pot = 2;
}
What would that even mean? Would it find every instance of Chamber
and set all their pot
s to 2? It's a nonsense.
A quick footnote: the language of the standard here is talking specifically about references, but to make the examples easier, I've been using non-references. I hope you can see this doesn't change the principle of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With