2

I've found in this question a strange syntax:

struct foo {
    int bar;
    int baz;
};

typedef int foo::*foo_member;
foo_member m = &foo::bar;

I still do not understand the type foo_member, what does type int foo::* mean?

Even more confused, what is &foo::bar in the initialization

foo_member m = &foo::bar;

and

foo AS1* f = /* ... */;
f->*m = 4;

I suppose that means f->bar = 4 (or not?), what does syntax f->*_variable_ mean?

Many thanks for any response.

Ta Thanh Dinh
  • 638
  • 1
  • 5
  • 12
  • 1
    `int foo::*` represent a pointer to member syntax. It define a pointer to integer that is a foo member. `foo_member m = &foo::bar; ` is storing the memory adress of the `foo::bar` member and storing in the pointer to member `foo_member m`. – Clonk Aug 08 '18 at 14:26
  • 1
    @Clonk what's tripping me up is `foo` is a type, not an instance, and `bar` isn't static. If that's valid, and not just an oversight in the example, it's pretty odd. – 3Dave Aug 08 '18 at 14:28
  • It's a pointer to an int member not a pointer to integer. This is how you would use it : `foo f; std::cout << f.*m << std::endl; ` – Clonk Aug 08 '18 at 14:30
  • @Clonk: thanks. It is a confused syntax, IMHO, `int foo::*` is a pointer to a member, but which member?. Moreover `&foo:bar` is undefined? (since `foo` is a type?) – Ta Thanh Dinh Aug 08 '18 at 14:31
  • @Clonk Yeah, I'm reading the spec now. Just seems that the committee could have found a way to do that inside the struct definition. Oh, well. :) – 3Dave Aug 08 '18 at 14:31
  • `int foo::*` is a **type**. `&foo:bar` is an instance of this type if you will (it has the type `int foo::*`) – Clonk Aug 08 '18 at 14:33
  • No `&foo::bar` is an object of type `int foo::*`, i.e. a "pointer to int member-of-foo". The valid values of `int foo::*` are `&foo::bar` and `&foo::baz` – Caleth Aug 08 '18 at 14:33
  • @Clonk: sorry `int foo::*` is a pointer type to a member (of type `int`) of `foo`. – Ta Thanh Dinh Aug 08 '18 at 14:37
  • Consider: `foo_member m = (rand() % 2) ? &foo::bar : &foo::baz; foo f { 42, 0 }; std::cout << f.*m;` The output depends on the choice of member – Caleth Aug 08 '18 at 14:39
  • That's pretty nifty. Though, I'd probably just add a reference `int& getIt() { return (rand() % 2) ? bar : baz; }` Shrug. – 3Dave Aug 08 '18 at 14:51

0 Answers0