I was reading a basic C++ tutorial when I faced
::*
in the following code. May I know what that is:
class A {
public:
protected:
int i;
};
class B : public A {
friend void f(A*, B*);
void g(A*);
};
void f(A* pa, B* pb) {
// pa->i = 1;
pb->i = 2;
// int A::* point_i = &A::i;
int A::* point_i2 = &B::i;
}
void B::g(A* pa) {
// pa->i = 1;
i = 2;
// int A::* point_i = &A::i;
int A::* point_i2 = &B::i;
}
void h(A* pa, B* pb) {
// pa->i = 1;
// pb->i = 2;
}
int main() { }
Based on my C++ knowledge so far, what is something like the following?
int A::* point_i2
It means that the variable is dereferenced twice. Assume you have a pointer to a pointer to char like this: char** variable = ...; If you want to access the value this pointer is pointing to, you have to dereference it twice: **variable.
Variable is basically nothing but the name of a memory location that we use for storing data. We can change the value of a variable in C or any other language, and we can also reuse it multiple times.
In C++, scope resolution operator is ::. It is used for following purposes. 2) To define a function outside a class. 3) To access a class's static variables.
It's commonly used to pack lots of values into an integral type. In your particular case, it defining the structure of a 32-bit microcode instruction for a (possibly) hypothetical CPU (if you add up all the bit-field lengths, they sum to 32).
point_i2
is a pointer to a member. It means that it points to an int
member variable that is declared in the class A
.
int A::* point_i2 = &B::i;
After this when you have a random A
or B
object, you can access the member that point_i2
points to
B b;
b.*point_i2 = ...;
After the above initialization of point_i2
, this would change b.i
.
Think of ClassName::*
the same way as you think of &
and *
: It's just another "pointer/reference-like tool" you can use in declarations to specify what the thing you declare is going to be.
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