954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

An array of class objects question

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!

dmanw100
Posting Whiz in Training
242 posts since Apr 2008
Reputation Points: 104
Solved Threads: 27
 

use vector

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

}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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...

Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You