Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer to member of a member?

Suppose I have two classes:

class A
{
    int x;
    int y;
};


class B
{
    int z;
    A ref;
};

Suppose I also have a function that accepts a pointer-to-member integer of B, like so:

void doSomethingToB(B* object, int B::* val)
{
    if(val)
    {
        std::cout << object.*val;
    }
}

Would there be a way that I could point to a member of ref inside B?

Like, int B::* ptr = &(B::ref.x) or something similar?

like image 812
Serge Avatar asked Aug 06 '12 23:08

Serge


1 Answers

This question gets asked from time to time

Is Pointer-to- " inner struct" member forbidden?

Basically, this can be described is a rather obvious initial oversight in the design of C++ language, which has has been ignored ever since due to the fact that the language develops in higher-level directions. Pointers of pointer-to-data member type are probably considered too low-level to be given enough attention. I wouldn't be surprised to discover one day that such pointers are deprecated instead of being developed further.

To repeat my statement from the linked answer, the low-level support is already there in every C++ compiler (since the low-level mechanism is the same regardless how deeply the member is "nested" - it is simply the offset of the member on the containing object), but the corresponding initialization syntax is missing.

like image 88
AnT Avatar answered Sep 22 '22 03:09

AnT