How to make multiple number of classes:
So you can choose: Should the number of objects be static or dynamic?
For static, you would do something like this:
The "tricky" part comes in if you want to make something dynamic.
Basically, you have 2 choices on how to do this.
1.
Make an dynamic array.
Basically, arrays are just pointers. So you can simply create an array with X numbers of elements doing this:
Code: Select all
ClassName* ObjectArray = new ClassName[NumberOfElements];
//Do stuff with it
delete[] ObjectArray; //Very important!
But a problem comes with this.
Array-Elements are created sequential, so you can imagine that as if they is just one big chunk in your memory, where all array-elements are stored in.
Because of this, you can "add to a pointer", e.g ObjectArray + 1 will give you the next element.
Now to the problem. Since arrays are build uppon this "one big chunk in memory", the PC cant guarantee that there is any free space near it - in case
you want to add elements. This would make the "ObjectArray + 1" unsafe, since it can just go out of bounds (e.g. the array continues 3 memory blocks further)
This makes the arrays kinda "unflexible", because you always have to make a new array,copy the old one to the new array and delete the old array.
2.
Linked Lists.
There are many ways to implement this, but I just explain the simplest one to you.
You can imagine linked-list like Objects floating around in memory and each object tells you where the next object is.
This way, you only have to know the first one, and then go from object to object till you reach the end.
Code wise, you have to change your class/structure a little bit.
Code: Select all
struct ABC
{
int I; //Some sort of data
ABC* Next; //A pointer to the next element
}
Now, to go through all the elements, you do something like this:
Code: Select all
ABC* Actual = Start; //Start is the first element you created
while(Actual != NULL) //There needs to be somekind of end condition. So the last element in the list just pointes to NULL as next element
{
cout << Actual->I << endl; //Print some data
Actual = Actual->Next;
}
But this also creates a new problem.
Imagine this:
On a 32bit PC a pointer to an object takes up 4 bytes of memory.
A integer does also take up 4 bytes.
If you now have 1000 integers saves in a linked list, they will take up twice as much space.
So now you have to choose.
If you simply want to make a game with the max. 3 bullets - go with static arrays
If you want to make a list of something known (e.g. if you load a map you already know the number of tiles) go with dynamic arrays.
If you have something like enemies that spawn all over the place, get killed, spawn again,... you'll want to make a list.
Just in case you dont want to implement your own list - you can use the stl implementation:
http://www.cplusplus.com/reference/stl/list/
Although, it might be a bit "overpowered" for your use, you can still consider it for starting/learing.
Hope that clears things up.