rahman
rahman

Reputation: 4948

What is ::* in C++?

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

Upvotes: 16

Views: 16451

Answers (2)

Andre
Andre

Reputation: 1607

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.

Upvotes: 13

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506965

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.

Upvotes: 6

Related Questions