2

Say I have a class I defined called 'MyClass'. My 'main' method takes as arguments a list of filenames. Each filename is a config file for MyClass, but the program user can have as many objects of MyClass as they want. If they type in, say, 2 filenames as arguments to my main method, I would like to have 2 objects.

If I knew the user was limited to 2 objects, I could just use:

MyClass myclass1;
MyClass myclass2;

However this wouldn't work if the user had say inputted 3 or 4 filenames instead. Can anyone help me and suggest a method I could use to create a number of insantiations of a class depending on the number of arguments my program is given?

Thanks

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
ddriver1
  • 723
  • 10
  • 18

3 Answers3

3

Use std::vector. Example

#include <vector>

std::vector<MyClass> vec;
vec.push_back(MyClass());
vec.push_back(MyClass());
vec.push_back(MyClass());

After that you can access the elements via [] and iterators and much more. There are excellent references on the web.

znkr
  • 1,746
  • 11
  • 14
2

You could use a std::vector of MyClass instances - then you could make as many or as few as you wanted.

Take a look at this tutorial, for example (one of many out there on the web), to get you started.

Nate
  • 12,499
  • 5
  • 45
  • 60
2

For this, you should use arrays or vectors:

vector<MyClass> myclass;

myclass.push_back( ... );  // Make your objects, push them into the vector.
myclass.push_back( ... );
myclass.push_back( ... );

And then you can access them like:

myclass[0];
myclass[1];

...

See wikipedia for more info and examples:

http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29#Usage_example

Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • vectors will work, arrays won't unless you know the maximum number of objects, and even then would be wasteful, because if you can have 100, but only use 1, you've wasted 99 object sized bits of memory. – Joel Oct 14 '11 at 17:43
  • 1
    @Joel: I was referring to dynamically allocated arrays as via `new`. But yes, your point holds for fixed sized arrays. – Mysticial Oct 14 '11 at 17:45