putting objects in an arry?

Started by
6 comments, last by oler1s 15 years, 5 months ago
can this be done in c++? if so how?
Advertisement
Well if you wanted an array of NUMBER_OF_ELEMENTS named my_array of type MyClass you would do:
MyClass my_array[NUMBER_OF_ELEMENTS];
This only works if MyClass has a default constructor, though.
no i mean say i have the class room, and i make 4 objects (a,b,c,d) with the classd room. can i store these objects in an arry?
Quote:can i store these objects in an arry?
Yes, and there are a few different ways to do so. For example:

// A static array (like SiCrane suggested):Room rooms[] = { a, b, c, d };// A boost::array (which is a fairly simple wrapper around a static array):typedef boost::array<Room, 4> rooms_t;rooms_t rooms = { a, b, c, d };// If you don't know how many rooms you're going to have, you'll probably want// to use a dynamic array class of some sort, e.g. std::vector:typedef std::vector<Room> rooms_t;rooms_t rooms;rooms.push_back(a);rooms.push_back(b);rooms.push_back(c);rooms.push_back(d);// If you have the Boost libraries available, you can shorten the above to:rooms_t rooms = boost::assign::list_of(a)(b)(c)(d);// This isn't recommended, but doing the memory management yourself would// look something like this:Room* rooms = new Room[4];rooms[0] = a;rooms[1] = b;rooms[2] = c;rooms[3] = d;// ...delete [] rooms;

As you can see, there are a number of different things you can do here. Which is the optimal solution depends on the circumstances.
Quote:Original post by Z_of_Thule
no i mean say i have the class room, and i make 4 objects (a,b,c,d) with the classd room. can i store these objects in an arry?

Do you want these objects to be in the variables a b c d AND the array? Because
Room rooms[] = {a, b, c, d};

will COPY the objects into the array.
no i want the objects to BE in the arry.
Then it's as SiCrane pointed out.

This topic is closed to new replies.

Advertisement