How exactly does constexpr double Point::* coords[3] work?

Viewed 107

So I've been looking at some stuff and found this thread Aliasing struct and array the C++ way

And this is the answer to the question

#include <math.h>

struct Point {
    double x;
    double y;
    double z;
};

double dist(struct Point *p1, struct Point *p2) {
    constexpr double Point::* coords[3] = {&Point::x, &Point::y, &Point::z};

    double d2 = 0;
    for (int i=0; i<3; i++) {
        double d = p1->*coords[i] - p2->*coords[i];
        d2 += d * d;
    }
    return sqrt(d2);
}

Now my problem is that I have no idea what

constexpr double Point::* coords[3] = {&Point::x, &Point::y, &Point::z};

is supposed to do...

I understand that constexpr makes it a constant that is defined at compile time and double is obviously used because the struct contains doubles but the Point::* and the {&Point::x, &Point::y, &Point::z}; confuse me. First of all what is Point::*? I guess the * means it is a some kind of pointer but to what? And what are these addresses {&Point::x, &Point::y, &Point::z} ?

What exactly does this entire expression define?

1 Answers

This syntax is a pointer to member, and is essentially a way to store a member to a variable and retrieve it. It's useful for a case like this, when you want to loop through a list of members.

Related