Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confused with an operator

Tags:

c++

operators

I confused when I try to understand the code below. Can anyone explain this hack:

a.*b

Or if a is a pointer to a class:

a->*b
like image 405
Aan Avatar asked Dec 26 '22 19:12

Aan


1 Answers

Both of those operators are used to dereference a pointer-to-member. Unlike regular pointers, pointer-to-members cannot be dereferenced by themselves, but must be applied to an actual object of the type. Those binary operators pick the object (or pointer) in the left hand side and apply the pointer to member to it.

struct test {
    int a, b, c;
};
int main() {
   int test::*ptr;
   ptr = &test::a;
   test t;
   t.*ptr = 5;         // set t.a to 5
   ptr = &test::b;
   test *p = &t;
   p->*ptr = 10;       // set t.b to 10 through a pointer
}
like image 63
David Rodríguez - dribeas Avatar answered Dec 29 '22 09:12

David Rodríguez - dribeas