16

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rahman
  • 4,820
  • 16
  • 52
  • 86
  • 8
    A "basic" C++ tutorial? No "basic" C++ anything should be covering member pointers. Do you have a link to that tutorial? – Nicol Bolas Mar 30 '12 at 08:27
  • @NicolBolas may be not very basic :) http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr129.htm – rahman Mar 30 '12 at 08:39
  • 1
    https://en.cppreference.com/w/cpp/language/pointer#Pointers_to_members – KaiserKatze Jan 18 '20 at 16:24

2 Answers2

12

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.

Andre
  • 1,577
  • 1
  • 13
  • 25
6
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.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • So is this like a "member class pointer"? Just like the method class pointers? – Gui13 Mar 30 '12 at 08:25
  • 4
    In simpler words. *Pointer to a class Member*. – Alok Save Mar 30 '12 at 08:25
  • @Gui what's a method class pointer? Do you mean `FunctionType A::*` ? Yes, they are the same. A pointer to data member has the member type be an object type, while a pointer to member function has the member type be a function type. Syntactically you can also use the function declarator syntax for the function type to make it look like `R (A::*)(parameters) cv-qual ref-qual except-spec`. Although if you are not familiar with C++ syntax it is easier to use alias templates and write `alias A::*`. – Johannes Schaub - litb Mar 30 '12 at 08:25
  • @Johannes: This (didnt find a clearer explanation on SO): http://mdzahidh.wordpress.com/2008/07/16/pointer-to-c-class-methods-or-should-you-call-em-method-pointers/ – Gui13 Mar 30 '12 at 08:26