So in my scripting project I mentioned yesterday I was thinking about how to implement arrays.
That got me to thinking how does c++ get arrays and inherited classes to interoperate and found out some wierd things
class Y
{
public:
int A;
Y()
{
A = 0;
}
};
class Z : public Y
{
public:
int B;
Z()
{
A = B = 0;
}
};
Y variables[4];
int main(void)
{
stuff[0] = Z();
stuff[1] = Y();
stuff[2] = Z();
stuff[3] = Y();
Z ztest = Z();
ztest.A = 8;
ztest.B = 9;
Y* testY;
Z* testZ = (Z*)&stuff[0];
testZ->A = 1;
testZ->B = 2;
stuff[2] = ztest;
testZ = (Z*)&stuff[0];
cout << "Z: " << testZ->A << "," << testZ->B << endl;
testY = (Y*)&stuff[1];
cout << "Y: " << testY->A << endl;
testZ = (Z*)&stuff[2];
cout << "Z: " << testZ->A << "," << testZ->B << endl;
return 0;
}
This kinda wierds me out becuase that means that if I make a class object Z and add it to an array of Z,Y objects to do a universal action than I'm inherently truncating data unless I make the array of pointers and augment the data that way and can't cast it back out. Which is not something I've really had to consider before.
Is this the reason more modern languages like C# use interface type situations and Handle Classes under the hood as references/pointers?