Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ::* in C++?

Tags:

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
like image 799
rahman Avatar asked Mar 30 '12 08:03

rahman


People also ask

What does *() mean in C?

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.

What does &variable mean in C?

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.

What is the :: operator in C++?

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.

What does colon mean in C?

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).


2 Answers

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.

like image 151
Andre Avatar answered Oct 16 '22 00:10

Andre


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.

like image 41
Johannes Schaub - litb Avatar answered Oct 15 '22 22:10

Johannes Schaub - litb