How to Dynamically Create Objects?

Nov 20, 2011 at 4:16am
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.
Nov 20, 2011 at 4:24am
Vectors!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <vector>

//...

std::vector<MyClass>  objects;

int numberOfObjects;

cin >> numberOfObjects;

objects.resize( numberOfObjects );

objects[0].DoSomething();
objects[1].DoSomething();
//... 
Nov 20, 2011 at 4:30am
Thanks a ton Disch!

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?

Nov 20, 2011 at 4:35am
A vector is a dynamic array.
Nov 20, 2011 at 4:49am
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 ?

I will have to research this.

Thanks again!
Nov 20, 2011 at 5:33am
Should I be using the vector class instead? Is it superior to just using the new operator with an array and a pointer ?


Pretty much, yes. There might be a slight performance tradeoff, but vectors are easier to use and safer. Less risk of leaks, easier to resize, etc.
Topic archived. No new replies allowed.