Search code examples
c++referenceoperator-overloadingsquare-bracket

What is returned by this operator overloading function?


I have the following listing from a page:

#include "vector.h"

// An axis-aligned bounding box
class AABB
{
  public:
    VECTOR P; //position
    VECTOR E; //x,y,z extents

    AABB( const VECTOR& p, const VECTOR& e): P(p) ,E(e) {}

    // ...

    const SCALAR min( long i ) const
    {

      return ((AABB*)this)->P[i] - ((AABB*)this)->E[i];
    }
    // ...
};

Now what I don't understand is, what is accessed by min() with a long value. I've looked into vector.hand found out that the square-bracket operator is overloaded:

class VECTOR
{
  public:
    SCALAR x,y,z; //x,y,z coordinates

    //...

    //index a component
    //NOTE: returning a reference allows
    //you to assign the indexed element
    SCALAR& operator [] ( const long i )
    {
      return *((&x) + i);
    }
    //...
};

Later it is used as:

// each axis
for( long i=0 ; i<3 ; i++ )
{
  if( A.max(i)<B.min(i) && v[i]<0 )
  {

So why is the x value reference incremented by i?
Please bear with me if this question is ridiculous easy, I am still a rookie. And if this isn't enough of information, I can provide the actual source


Solution

  • It's not incremented.

    &x  //<- address of member x
    (&x) + i //<- address of member x shifted right by i SCALAR's
    *((&x) + i) // the scalar value at that point
    

    Hence *((&x) + i) returns the i'th scalar. x for 0, y for 1, z for 2.