Arrays or Objects?

Hi all,

I am just getting into the world of OOP and I'm not totally sure in what situations it's better to use objects and when it's simpler to just revert to arrays.

For example, I am currently re-writing a bit of scientific code written in C that simulates the evolution of the solar system. The crux of the simulation lies in the particles in the original disc of material, which has certain properties such as mass.

In the original C code this is simply implemented as different arrays for each characteristic of the particles, with each row of each array corresponding to a particular particle. This way, during the simulation, when checks have to be performed on the particle, a simple for-loop is used along the rows of the arrays.

It seems to me however, that in terms of OOP, these particles can also be represented as objects of a particle-class that contains all the characteristics of each particle. The only problem I have in implementing this is that I have to instantiate about 1000 such particles i.e., 1000 objects and I don't know if this is less efficient than just putting the characteristics in different arrays. In addition, during the simulation I would have to have a way to scan each of the 1000 objects. This is simple enough with an array and a for-loop but I don't know how this would work with a group of objects.

Anyway, basically my question is therefore whether in this situation simple arrays are a better way to go, or should I create a class for these particles? If the latter, how do I then manage the objects during the simulation?

Thanks in advance,

Regards,

Kartik
Arrays and objects are orthogonal, but I understand what you are trying to ask.

You are right in that it makes more sense to aggregate all the characteristics into a single class
and then make an array of classes.

The following are equivalent in terms of memory usage and cpu usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int particle_masses[1000];
int particle_x_coords[ 1000 ];
int particle_y_coords[ 1000 ];
int particle_z_coords[ 1000 ];

// and

class Particle {
    public:
         int mass;
         int x;
         int y;
         int z;
} particles[ 1000 ];


Hi Kartik,

If it is the requirement for porting C code into C++, then go with Class and Objects otherwise stick with array becz already the C code may completely tested and it has been working well. So you have to test those testcases again thoroughly, waste of time. If u are going to do any new enhancement or development, do it in C++. Accessing the C code in the C++ is very easy.

Thanks,
Harini.
In general an object-array wrapper is easier to use, more powerful and more efficient than an array. Compare std::vector to arrays. Vector is better in nearly all cases. (On the other hand, a linked-list container such as std::list might not be as easy to use as an array because these containers don't support subscript.)
Last edited on
Topic archived. No new replies allowed.