I want to store 3 properties of 1000 rectangles. I can do that in two different ways. I can use a structure or an array, but I try to find out which solution uses least memory. Here the code:
struct Figure {
unsigned int color;
virtual void foo() {}
};
struct Rectangle : public Figure {
unsigned int width,height;
};
int main() {
Rectangle r[1000];
unsigned int r2[1000][3]; //This take less memory, The first entry is rectangle number
// the next is color, width and height
std::cout<<"Type name is "<< typeid(r[0]).name() <<sizeof(r2)<<" "<<sizeof(r)<<std::endl;
return 0;
}
The output is:
Type name is 9Rectangle12000 24000
As you can see an array of objects of a structure uses twice as much memory as a plain array. Why is it so? I expected that an array of structures in my case would use more memory because of the polymorphic structure, but not that much.