MSalters
MSalters

Reputation: 180050

Can you have a "pointer to member" to a member of a union?

All descriptions that I can find talk about "pointer to member" in the context of a class. Unions are very similar to structures, and in particular have members too. Can you have a pointer to those members too?

E.g.

union x {
    int a;
    float b;
};
int x::*p = &x::a;

I'm not talking about pointer to the union as a whole, pointers as members of a union, etc. p in the example above would really be an offset, obviously of size 0. I'd need this construct to answer this question.

Upvotes: 5

Views: 1280

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137910

§3.9.2/1: Compound types can be constructed in the following ways: … pointers to non-static 50 class members, which identify members of a given type within objects of a given class,

§8.3.3/1: In a declaration T D where D has the form … and the nested-name-specifier denotes a class, …

§5.3.1/3: The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id. If the operand is a qualified-id naming a non-static member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::m.

And of course §9.5/5: A union is a class defined with the class-key union

(§3.9.2/1 also mentions: unions, which are classes…)

No mention that the class cannot be a union, so yes, you can form such a PTM type and value.

Upvotes: 5

Related Questions