I have a program that has a custom class that I would like to create many of and access them like an array. Example:

#include <iostream>
using namespace std;

class Thing
{
    public:
             Thing(int value)
             {
                  a = value;
             }
             int doStuff(int diffValue)
             {
                  a = diffValue + a;
             }
    private:
             int a;
};

int main()
{
    Thing things(12)[100];
    things[4].doStuff(12);
    return 0;
}

Obviously that will not work but is there an easy way to do this? I am not too familiar with pointers but if there is an easy way to use them in this case...
Thanks I'm open to any suggestions!

Recommended Answers

All 2 Replies

use vector

#include <vector>
...
int main()
{
    vector<Thing> things;
    Thing oneThing;
    // add OneThing to the vector
    vector.push_back(theThing);

}

and you need a default constructor of the class too, since you have declared your own ctor the compiler will not generate it for you...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.