I occasionally see bits of code similar to this:
class A {
int b;
}
void foo() {
int* blah = &A::b;
// Other stuff.
}
But how could grabbing the address of a class’ member variable without an instance of the class be useful? What does it do?
Your code is ill-formed and will not compile. The type of
blahis notint*, it isint (A::*). That is, it is not a “pointer to anint,” it is a “pointer to a data member of class typeAwhose type isint.”Note that in order to obtain a pointer to a member, the member must be accessible. To compute
&A::binfoo(),bwould need to be a public data member, orfoo()would need to be a friend ofA.A pointer-to-member does not point to an object. Rather, a pointer-to-member can be bound to an object to get the value of its data member. You can obtain the value of the
bdata member of anAobject by binding theblahpointer-to-member to the instance ofA. For example,