Is it legal to apply a pointer variable to a derived member class to a pointer variable to a base member class?

Does the following undefined behavior occur if the pointer used to access the member pointer is of the correct type?

And if so, why should I? It would be much better with him (and yes, I know that this is only a matter of opinion).

struct base {
    int foo(int base::* ptr) {
        return this->*ptr;
    }
};

struct sub : base {
    int blah{ 42 };
};

int main() {
    return sub{}.foo(static_cast<int base::*>(&sub::blah));
}
+4
source share
1 answer

Does the following undefined behavior occur if the pointer used to access the member pointer is of the correct type?

No, he is well formed. Rule from [expr.mptr.oper] :

If the dynamic type E1 does not contain the member to which E2 belongs, the behavior is undefined.

The dynamic type *this is the subone that contains the element, so this is normal.

And if so, why do I need a listing?

, , . , , . , .

. ( , ..) a Derived* Base*. , . Base* Derived*... Derived*. , - , . , , .

+6

Source: https://habr.com/ru/post/1685571/


All Articles