0

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.

n33ter
  • 27
  • 1
  • 4
    I recommend you get yourself a better [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Your code has undefined behavior. See: https://stackoverflow.com/questions/40590216/is-it-legal-to-index-into-a-struct – NathanOliver Jun 03 '21 at 15:23
  • 1
    The code takes the assumption, that the the class members x,y,z are in the memory as they will be if you use an array of double[3]. But I fear that this may be undefined behavior if the compiler use gaps in between. I am not sure if it is guaranteed that the operator[] will guarantee correct access. I don't believe. Ah! Nathan already points the the answer: It is UB! :-) – Klaus Jun 03 '21 at 15:25
  • 1
    I think this should be a duplicate of the second link @NathanOliver gave – drescherjm Jun 03 '21 at 15:27
  • Change *undefined behavior* `double &operator[](int i) { return ((&x)[i]); }` to `double &operator[](int i) { if (i == 0) return x; if (i == 1) return y; if (i == 2) return z; throw std::logic_error("oopsies"); }` – Eljay Jun 03 '21 at 15:27

0 Answers0