tags:

views:

272

answers:

3

I was looking through the source of OpenDE and I came across some wierd syntax usage of the 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 operator[] for Point isn't overloaded in anyway and here this code is trying to do an automatic conversion to float somewhere. I've never seen this kind of usage before and it looks unusual to me.

Thanks

+14  A: 

p is being converted implicitly into a float*, which points to x. So *p is x, *(p+1) is y, and so on. It's a pretty weird idea (and confusing!) to do it this way, of course. It's usually preferable to store x, y, and z in an array and have a function to get the entire array if they really want to do things this way.

rlbond
Not to mention that this is completely unsafe since the location in memory of `x`, `y`, and `z` isn't well-defined.
D.Shawley
ahhh okie thanks. That's some clever code there... maybe too clever :o
Victor T.
@D.Shawley: A good point. While a "reasonable" compiler probably would do this, I don't believe there's any guarantee that this layout is standard.
rlbond
Another downside is that if you accidentally use a Point as a boolean value it will mysteriously "work" and always give true, because it coerces Point -> pointer -> boolean
Henk
@Henk: I was under the impression that this coercion is not automatic because anything more than A->B is not allowed.
rlbond
@rlbond you're thinking of operator->(). Try this:class A {public: operator void *(){return 0;}}; int main(int argc, char *argv[]) {if(A()) {printf("true\n");}else{printf("false\n");}}
Henk
Given that the members all belong in the same access control section (are all private), I believe that they are guaranteed to be laid out sequentially in order of declaration. If one was public, another protected and the other private, then there would be no guarantee of the relative ordering. ISTR reading that in Lippman's "Inside tThe C++ Object Model" when I reread that recently. (I'm not really defending the coding style - it is obnoxious; but neither am I convinced it is as undefined as is implied by other comments.)
Jonathan Leffler
@Jonathan Leffler, you are right, it is guaranteed by the C++ Standard 9.2/12: "Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object."
Kirill V. Lyadvinsky
@Jonathan Leffler: the order is guaranteed but there is not guarantee that `y` immediately follows `x`. The compiler is free to insert padding for whatever reason.
D.Shawley
+1  A: 

This is just a way of treating your member data as an array. You can also do this with structs. This is useful when you want readability, yet want to be able to iterate over simple data structures. An example use would be to declare a matrix this way:

typedef struct {
   CGFloat m11,m12,m13,m14;
   CGFloat m21,m22,m23,m24;
   CGFloat m31,m32,m33,m34;
   CGFloat m41,m42,m43,m44;
} CATransform3D;

You can conveniently reference each cell by name, yet you can also pass around a pointer to m11 everywhere (and C will see your struct as an array, m11 being the first element), and iterate over all the elements.

vdeych
+6  A: 

The idea here is to give access to the members of the Point by either subscript or name. If you want to do that, however, you'd be better off overloading operator[] something like this:

struct Point { 
    float x, y, z;

    float &operator[](size_t subscript) { 
        switch(subscript) {
            case 0: return x;
            case 1: return y;
            case 2: return z;
            default:  throw std::range_error("bad subscript");
        }
    }
};

This way, if the compiler inserts padding between the floats, it will still work -- and anybody who can read C++ should be able to understand it without any problems.

Jerry Coffin
@Jerry Good point. That's what I'm thinking too. I know when I was perusing the source, it wasn't obvious what the code was doing. I think this definitely falls under 'code that's too clever for its own good'. :P
Victor T.
+1 for the 'proper' code - safe, handles errors, readable, etc.
JBRWilkinson