What does this C++ syntax mean and why does it work?

Viewed 592

I was looking through the source of OpenDE and I came across some wierd syntax usage of the array indexing operator '[]' on a class. Here's a simplified example to show the syntax:

#include <iostream>

class Point
{
public:
    Point() : x(2.8), y(4.2), z(9.5) {}

    operator const float *() const
    {
        return &x;
    }

private:
    float x, y, z;
};

int main()
{
    Point p;
    std::cout << "x: " << p[0] << '\n'
              << "y: " << p[1] << '\n'
              << "z: " << p[2];
}

Output:

x: 2.8
y: 4.2
z: 9.5

What's going on here? Why does this syntax work? The Point class contains no overloaded operator [] and here this code is trying to do an automatic conversion to float somewhere.

I've never seen this kind of usage before -- it definitely looks unusual and surprising to say the least.

Thanks

3 Answers
Related