I've been wondering what the simplest way of creating a varying number of objects of a (of the same) class could be.
For example, suppose I ask the user for an integer through std::cin and make the program create the same number of objects that the user entered. Or lets say I want to define a function that does something to the objects but does not know beforehand how many objects it is going to be handed.
It ocurred to me that the smartest way would be to create an Array of the class objects, something like this
1 2 3 4 5 6 7 8 9 10 11 12
class A {
(...}
)
main () {
int n;
std::cin>>n;
AObjects[i] Blabla;
}
However, I feel like there must be another way. Handling a whole Array to a function feels kind of heavy when a function might not even be using all of its entries. I thought maybe Enums could help me, but I dont understand them to be frank, so maybe I am on the wrong track here. :)
Array is one way of doing it. But it wouldnt work just doing it the way youve done it in your example. If you want to create a user-defined-sized array you'll have to allocate memory for it on the heap.
That's why std::vector is far superior to arrays and you should learn how to use them. There is lots of info on youtube and google.
With a modern C++ compiler dynamically creating a fixed-size array won't work as you have done in your code snippet, even if you use the C++11 array class container. It won't compile.
Thanks for the replies. I know that the cost I posted is fishy, should have looked closer before posting it.
The strange thing is, I already managed to compile similar pieces of Code, where I got the users desired Array-length with std::cin and then created an array the size of the variable.
However, I do think that allocating memory is the correct way to do it and I will get into that.
Regarding my original Question, are there better ways to do this? Or is the vector-function basicalle the best option I got? I really don't know much about programming efficiently yet, so you are helping me a bunch here.