Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have a pointer to a data member of a subobject's class?

I've got interested in one thing - in c++ we have pointers to data member, for example:

struct A
{
  int a_1 = 1;
};

A a;
int A::* p_a = &A::a_1;
    
a.*p_a = 10;

But if I have something like this:

struct B
{
  int b_1 = 11;
};

struct A
{
  int a_1 = 1;
  
  B b;
};

... where an object of type B is stored in an object of type A - is there way to have a pointer to a data member of a subobject's class, i.e. something like this:

A a;
/*???*/ p_b = &A::B::b_1;

a.*p_b = 10; // after that - a.b.b_1 is equals to 10

Hope I made myself clear:)

like image 396
Ultra_Igor Avatar asked Sep 01 '25 23:09

Ultra_Igor


1 Answers

Your combined pointer to member is just two separate independent pointers to members of individual struct (a bit like a 2D array index is just a pair of regular 1D array indices).

auto [pa,pb] = std::tuple(&A::b, &B::b_1);
a.*pa.*pb = 42;

If you prefer a single operator syntax like a->*pab, you need pack the two pointers to members into a single object, and overload operator->* for it. This is a rather trivial exercise.

like image 184
n. 1.8e9-where's-my-share m. Avatar answered Sep 03 '25 13:09

n. 1.8e9-where's-my-share m.