Is there a way to store each Fruit object into list[100] without typing out "list[0] = apple, list[1] = pear....etc"?

And, is there a way to use sizeof on a class, to count the number of objects it has? So I can make list[] hold the same number elements as Fruit has objects.

I'm trying to code in a way so when I add more objects later down the road, I will only have to initialize them in their class. Rather than have to do that, and change array sizes, and values and all that.

Much appreciated,

05-30-2010

CodeMonkey

Quote:

is there a way to store each Fruit object into list[100] without typing out "list[0] = apple, list[1] = pear....etc"?

Not if each fruit is a distinct instance declared somewhere -- in that case you'd have to add them one-by-one. You could make it easier by adding them when your declare them, or by keeping a map<string,Fruit*> handy throughout the program.

Quote:

And, is there a way to use sizeof on a class, to count the number of objects it has? So I can make list[] hold the same number elements as Fruit has objects.

Library containers like std::vector have size() and can be resized dynamically. Otherwise, you'd have to keep track with an int size, or better yet with your own custom class. Or use vector :)

Quote:

I'm trying to code in a way so when I add more objects later down the road, I will only have to initialize them in their class. Rather than have to do that, and change array sizes, and values and all that.

You can add fruit to your array (let's say vector) anytime you like, and they'll be copied right in. If you mean that you want the fruit to add itself to the list, then you might find tricky constructor stuff heading your way (I say from ignorance). You could also

Thank you very much, this basically answered all of my questions. My Fruit list[100] is just a normal array. I didn't even think of actually using a list.

I'm pretty inexperienced, so I don't understand how you are using the '&' sign in your code;I haven't used vectors or lists yet. push_back seems to do exactly what I'm looking for though, so I will learn more about them

Thanks again.

05-31-2010

CodeMonkey

The & indicates a reference. You can look it up on this website and have a full understanding of it in a minute. It's just an alias -- a way of having another name for something in scope, without having to declare and dereference a pointer.