Say I have the following test code:
#include <iostream>
using namespace std;
class Vector3 {
public:
float data[3];
};
class Weird3 : public Vector3 {
public:
union {
struct { float &x, &y, &z; };
struct { float &r, &g, &b; };
};
Weird3() : x(Vector3::data[0]), y(Vector3::data[1]), z(Vector3::data[2]) {}
};
int main(int argc, char** argv) {
const Weird3 w;
w.x = 100; // Works ok!
cout << w.x << endl;
w.data[0] = 100; // Error: assignment of read-only location
cout << w.x << endl;
return 0;
}
Why does modifying data
member through the reference member in the child class works, but not directly? Also, is there a better way to achieve this behavior? For example, I have a template class VectorN
, and derived classes Vector2
, Vector3
and Vector4
; I would like to modify the data
member in VectorN
using members in child classes like x
,y
,z
or r
,g
,b
.