Search code examples
c++compositionmember-pointers

Can I compose pointers to member


I'd like to compose member pointers. Basically I have a main class with different member. How do I create a member pointer for the main class that would point to a member of a member of that class. I hope the code below is explains what I'm trying to do:

  struct SubUnit
  {
    int   value;
  };
  struct Unit
  {
    SubUnit sub_unit;
  };

  void Test()
  {
    SubUnit Unit::* ptr1 = &Unit::sub_unit; // WORKING
    int Unit::* ptr2 = &Unit::sub_unit::value; // NOT WORKING !
  }

Solution

  • The use of sub-class is confusing here, since generally sub-class is used for inheritance, so let us talk about a data member: sub_unit is a data member of Unit.

    And what you are asking for is not possible, Unit::* can only represent an offset in either Unit itself or one of its base-classes:

    struct SubUnit { int value; };
    
    struct Unit: SubUnit {};
    
    int main() { int Unit::* p = &Unit::value; }