views:

548

answers:

5

I'd like to generate a number of objects (in C++) based on the amount/number the user enters.

Now I've somewhere heard that it has to be done using pointer tricks, creating a pointer to an array of the Object type required, and then dynamically increasing the size of array ( at runtime ).

Isn't there a workaround of directly using names like Object1, Object2..... ObjectX instead of having Classname *Object[] and then using the array index to get the object ?

In either case, it'd be great if someone could clarify on the issue.

Thanks !

+5  A: 

If you want dynamically-sized array, then use std::vector. You won't be able to resize a built-in array. If you want to be able to get an object by string name, then you should use std::map, it has an indexer:

std::map<string, Classname> myMap;
myMap["Object1"] = Classname();
Classname newClassname = myMap["Object1"];
Dmitry Risenberg
+1 to compensate the unexplainable down-vote -- a map is a fine approach if you want to deal with objects by string-name rather than by number.
Alex Martelli
Thanks for the idea regarding maps. I sure will take a deeper look into it as well.
suVasH.....
+3  A: 

No, there isn't. Moreover, you don't need to; use std::vector.

David Seiler
+3  A: 

When I began programming 9 years ago I asked myself the same question. The answer is: you can't.

You can indeed use an array and resize it dynamically, however using an stl vector is much easier (once you learn how to use it).

StackedCrooked
9 years ago you say :) that makes me have to wait a long while, hehe ! really appreciate the reply !
suVasH.....
+2  A: 

You can not do that because C++ doesn't have an "environment" (reflection) where variables (and metadata) can reside. Moreover, in C++ all variable names are vanished when the code is compiled.

A way to achieve the effect you want is to use a Map where the keys are strings.

Nick D
Thanks again for the idea with maps. I sure will take a look.
suVasH.....
+5  A: 

So far no-one has explained why your thinking is flawed. C++ is a compiled language, and it goes to great lengths to turn the source program into efficient machine code. For this reason, the names you give variables are available to the program only at compile time, when you turn it from source into an executable file. Afterwards, when you want to create objects dynamically, those kinds of information are no longer available. The program only knows about the machine addresses where operands to machine instructions are located.

TokenMacGuy
Thanks for the explanation, exactly what i needed (to understand). Cheers !
suVasH.....