Accessing Class Member Variables with [] operator

  c++

I’m going through a book and I saw something interesting that I don’t quite understand how it works.

What is happening under the hood of C++? Are the member variables laid out in an array like fashion. Does it only work for member variables of the same type?

I added a string type as the fourth variable just to see what happens and the output for [3] is 1.75518e-317.

Vector3D b{1, 2, 3, "56"};

cout << b[3] << "n";

Here is the code:

vector.h

public Vector3D {
public:
    double x;
    double y;
    double z;
    Vector3D(double a = 0.0, double b = 0.0, double c = 0.0)
    {
        x = a;
        y = b;
        z = c;
    }
    double &operator[](int i)
    {
         return ((&x)[i]);
    }
}

main.cpp

int main(int argc, char const *argv[])
{
    Vector3D a{1, 2, 3};
    Vector3D b{1, 2, 3};
    cout << b[0] << "n";
    cout << b[1] << "n";
    cout << b[2] << "n";
    return 0;
}

Output:
1
2
3

Note: This code is a learning exercise only and I am not using it for anything.

Source: Windows Questions C++

LEAVE A COMMENT