How do I dynamically create objects iteratively during runtime without knowing the amount beforehand?
This illustrates the idea of what I'm trying to do, not the implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int numberOfObjects;
cin >> numberOfObjects;
// For my example lets pretend this time the input is 100
for(int i=1; i <= numberOfObjects; i++) {
MyClass object1;
MyClass object2;
// continue same pattern
// ...
MyClass object98;
MyClass object99;
MyClass object100;
}
Hopefully, my question was not asked too confusingly.
If anyone would be willing to explain a good way of doing this or point me in the right direction I would be very grateful. Thanks! :)
PS- I am pretty new to programming so sorry if this is a dumb question. I only found a few relevant results on google and I couldn't understand them super well.
That kicks ass! This will work perfectly for what I had in mind. I didn't know I could use vectors that way. Am I correct in assuming this also works with dynamic arrays?
I know. I meant dynamically allocating a normal array.
Something like this:
1 2 3 4 5 6 7 8 9 10
int numberOfObjects;
cin >> numberOfObjects;
MyClass* array;
array = new MyClass[numberOfObjects];
// etc.
I have to admit that, while I know vectors exist, I've never really used them yet. This is because I learned how to create dynamic arrays without it first, and haven't bothered to learn the vector class thingie yet. I've been just doing it like in my example above.
Should I be using the vector class instead? Is it superior to just using the new operator with an array and a pointer ?