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

Viewed 170

Does the following lead to undefined behavior as long as the pointer being used to access the pointer-to-member is of a correct type?

And if so, why do I need the cast? It would look a lot nicer without it (and yes, I know that's just 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));
}
1 Answers
Related