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

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

2 Comments

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: I was referring to dynamically allocated arrays as via new. But yes, your point holds for fixed sized arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.