Creation of Multiple Objects

I'm a casual programmer and I'm trying to broaden my knowledge of C++.

I am fascinated by Object Orientated Programming and I am trying out a small project of my own but my project calls for many copies of the same or similar objects. I then want to group all the objects together into a second object. I therefore have two questions

Firstly is there an easy way to create 10, 20 or more of the same object through a simple loop rather than declaring each and every one individually? All the text books I have give examples which only have 2 or 3 objects and each one is declared individually through main(). This works when you have a couple of objects to play with but I need minimum 30!

Secondly how do you go about making a second object that is the sum of all the smaller parts of the first? For example:

20 Objects of Class A = 1 object of Class B.

I thought the best way to do the second part would be for Class B to declare all the individual objects of Class A and then store them in either an array or vector. Is this workable? If so how do I go about doing it?

I would really appreciate a couple of pointers on this!

Thanks in advance!

Yes, you can create multiple objects like that by declaring an array of them.

 
Class_A A[20];

You were probably over thinking it, that happens a lot.

Keep it simple and use the array I mentioned before. Unless this second class will have functions to use with the objects, even then I would check out the STL containers first to see if it is already written: http://www.cplusplus.com/reference/stl/
Last edited on
Yes, you can create multiple objects like that by declaring an array of them.

Class_A A[20];

You were probably over thinking it, that happens a lot.


I knew there must be an easy way of doing it! Thanks Computergeek01!

One more thing. Would this work if the objects in class A were slightly different? Lets say that class A has 5 objects called "Cherry" and five objects called "Banana". How do you create an array that would hold all 10 without declaring each one separately?
In that case, you would create a pointer array (read: a ptr_vector) of fruits, which of course assumes that they inherit from a Fruit class.
Topic archived. No new replies allowed.