I have a structure called scene. Within the structure called scene, I need to make an array of other scene objects. Is this possible?
4 Answers
No, because before scene is completely defined, the compiler doesn't know how big it is, and doesn't know what size to make the array.
However, you can have an array of pointers to scene, because pointers (not counting pointers to members and other oddities - thanks Nawaz) are all the same size:
class scene {
scene* array[20];
};
Alternatively, you can store a pointer that will point to a dynamic array allocated with new[] and deallocated with delete[]:
class scene {
scene() : array(new scene[20]) { }
~scene() { delete[] array; }
scene* array;
};
or even more alternatively, store a vector<scene>, a vector of scenes:
class scene {
vector<scene> array;
};
and with vector, you get a resizable array with no manual memory management.
7 Comments
because pointers are all the same size. Not all pointers are necessarily of same size. He can use pointers, not because "pointers are all the same size.", rarher because the compiler already knows the size (whatever it is) of pointer of particular type.T, sizeof(T*) == C where C is a constant integer. How does the compiler know how big the pointer will be to that particular type if it's not defined yet? Or what would make one pointer bigger and one smaller than another? And if that's true, you can't cast any pointer to any other type of pointer without possible loss of information, right?Yes. You can do that. But you've to declare the member as pointer as:
struct scene
{
//other members
scene *children; //this is what you need.
//you cannot make it like : scene children[100];
};
Then create the dynamic array as:
scene parent;
parent.chidren = new scene[100]; //100 children!
Just remember that you've to allocate and deallocate the memory yourself.
Alternatively, you can use std::vector<scene*>, or boost::ptr_vector<scene>.
struct X { X a };?