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

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 scientific code it is normally best to ensure that the code is clearly readable, and reusability is less important than most OOP, but it useful to have both at all times

The first thing you need to do is be sure of what you need for each particle:
mass
position (this might be a coord xyz for a local origin)
speed (coord xyz)
spin
volume

The you might need a time frame handled seperately
update each coordinate check for collisions then decide whether
a particle breaks-up sticks to another particle bounces.

It is important to get the system working before optimisation

Arrays have a short shelf life and can introduce magic numbers if
you have an array of X values and Y values what happens if you miss one on input?

what you can use is a std::vector<particles>
this is #include <vector>

then if you can iterate over the vector in a for loop
getting the particle speeds have
if you put this in a class with methods

add_particle(particle &p);
update_particles();
change_particle(particle & p, int new_state);
advance_time();
you can control the methods:

but if you can be clearer over the design the problem becomes simpler there will always be an OOP that is similar to the non-OOP but it is more flexible for changes. If you can be more specific of the information you need to track a better answer could be given.


You will want to use OOP
You probably do want a particle object to decide what happens with collisions etc.
but it is possible that a particle is not meaningful for your calculations

The simulation is based on a simple planetary disc model, so the only properties I need to track of the particles are: mass, semi-major axis, eccentricity (latter two are parameters of the orbit of the particle).

So basically the code written in C now has 3 arrays: mass[], semiMajorAxis[], eccentricity[], each of size N, where N is the number of particles in the system at initialization of the disc.

The model is based on particle accretion using totally inelastic collisions. It is not a time-based simulation, but rather a statistical ensemble.

Right now at each step, the simulation scans the property arrays and determines collisions (based on secular limit), through the use of for-loops.

Indeed, the thing I am worried about with using arrays is the lack of checks inherent in C++ e.g., out of bounds check.

I know I can get around this by using the vector class in the standard library, but I was wondering if it made more sense in this case to actually create a class for the particles. I thought of storing pointers to objects of the class as a way of then being able to track them during the situation, but then I'd be storing the pointers in an array, which is what I attempted to avoid in the first place.

I have an environment class that determines the global conditions of the simulation and an event class that determines what happens due to an event in the simulation e.g., collision.

Just not sure what the most efficient way is programming the particles. Efficiency is important because the faster the code is, the more particles I can include in the model and the more simulations i can run.

Thanks in advance,

Kartik

For scientific code it is normally best to ensure that the code is clearly readable, and reusability is less important than most OOP, but it useful to have both at all times

The first thing you need to do is be sure of what you need for each particle:
mass
position (this might be a coord xyz for a local origin)
speed (coord xyz)
spin
volume

The you might need a time frame handled seperately
update each coordinate check for collisions then decide whether
a particle breaks-up sticks to another particle bounces.

It is important to get the system working before optimisation

Arrays have a short shelf life and can introduce magic numbers if
you have an array of X values and Y values what happens if you miss one on input?

what you can use is a std::vector<particles>
this is #include <vector>

then if you can iterate over the vector in a for loop
getting the particle speeds have
if you put this in a class with methods

add_particle(particle &p);
update_particles();
change_particle(particle & p, int new_state);
advance_time();
you can control the methods:

but if you can be clearer over the design the problem becomes simpler there will always be an OOP that is similar to the non-OOP but it is more flexible for changes. If you can be more specific of the information you need to track a better answer could be given.


You will want to use OOP
You probably do want a particle object to decide what happens with collisions etc.
but it is possible that a particle is not meaningful for your calculations

If you have a system with 1000 particles the information you will need to save/enter will be the same whether you have individual particles, arrays of attributes or a container of particles.

Who said you won't have to worry about out of bounds checking when using vectors? To my knowledge the big advantage of using vectors has to do with memory handling and keeping track of things like size, empty, etc, not bounds checking. Having said that, if you are going to be resizing the system from 1000 to 5000 or 10000 or whatever, then using a vector might allow a smoother "scaling up/down" of the system than using arrays.

IMHO, using iterators instead of indexes to control looping through a container is 6 of one and half an dozen of the other.

Using classes you can sometimes automate things a little bit. For example, if a change in one attribute automatically changes other attributes you can create a method to change all the attributes and just call that one method instead of manually figuring in the changes. Or if you want to do a lot of sorting by attributes, etc, you can often write a little more code early on to limit the code you need to write later, etc.

Using classes does promote the possibility of reuse in a later project, particularly if the classes are declared in a header file as opposed to directly within the program, but that might not be that important.

All in all, I think you can use whichever style, parallel arrays/vectors or arrays/vectors of objects, that you feel most comfortable with, unless, form your point of you you can make a major benefit out of what appears to be minimal potential benefits.

Well I did ask :) , I had to look-up a lot of the scientific terms and even then some areas are still very complicated.

So you have a statistical model of objects rotating ~in a plane towards a centre so that
the system becomes viscous and slows down.

My concern is that you have a particle that has mass, yet the properties that
are being stored are not representative of a particle object but would be an orbit object.
with code like this it is essential to know what represents meaningful elements to your
calculation.

Fully optimised code will not be suitable for another purpose, but minimal overhead is only going
to be a few seconds to allow code to object orientatede and re-usable. There has to be an awareness
that your time in writing, error proofing and maintaining the code can be the most time critical issue.

Now you can iterate over arrays quickly as a[1000] has a pointer 'a' but it can get tricky
to read what exactly you are doing at each step.
It is often beneficial to take advantage of existing solutions and there will be a lot of common tasks
this makes the use of vectors preferable in my opinion.

With vectors they are built for speed so can overflow if you misuse them.
But what you can easily do with vectors is have a test problem with fewer particles / inputs without
the need to change any code other than change an init() which could load from file.


As for efficiency - optimisation is important but often focusing on the overhead of function pointersis missing the key time factors.

- You need to be able to check that what you have coded is what you think that you have asked the computer to do
You want a modular design :
- then you can run the program in stages
- Test a block individually and alter the code at one place easily
- reusable for other purposes

an important class if optimisation is important is clock_t found in <time.h>

This allows a method of timing how long each block takes. When talking about iterators or
a access in order the iterator can be significantly faster it certainly was in the past.

When timing and running C++ code with visual studio you should use Release mode not Debug with
visual studio it can have very dramatic influence on speed.

In most collision systems, it is checking for collisions that is the time dominant factor, you
need to check what order collisions happen and then recalculate any collisions that might happen as
a consequence of the original collision. It is this area where your design needs to be aware of
solutions that you might want to implement. If your particles are not being treated independently
then a crude approach needs to check 999 * 498 pairs of particles every time a decision changes, yet, it
is likely that not all of the 0.5 million path interactions will need to be done every time there is a collision.

If a zonal system is possible with your statistical method then a pair structure with each
orbit as pointers and G pre-calculated might be appropriate so you could then delete values from the vector

The first thing you need to design is your events class what methods do you need?

It is likely that you might need a temporary container of values before deciding which ones to update.

It is also possible to use duplicated versions of values but then you need to carefully manage the sychronisation.

When you describe a run as long are we talking 1 hour, 4 hours or 100 hours?
4 hours can be run without worrying about update shutdowns and finding all the mistakes before the
first run.

//how you might use vectors

#include <vector>
using namespace std; //to avoid std:: before vector
void main()
{

//this could go in a management class
vector<double> masses, eccentricites, semi_major_axes;

int likely_number_of_particles(1000);
//an example of a way to prepare the systrm 
masses.reserve(likely_number_of_particles);


//add a particle this would sit in a function

double mass(100), AU_radius(15), eccentricity(0.9); 
//add to the end
masses.push_back(mass);
semi_major_axes.push_back(AU_radius);
eccentricities(ecentricity);

//this will give a warning could use size_type to avoid
int sz = masses.size();

//now you can use vector like an array

for(int i(0); i < sz; ++i)
{
	double cur_mass = masses[i];
}

//for larger vectors this will be faster
vector<double>::iterator it_stop = masses.end();
for(vector<double>::iterator it(masses.begin()); it != it_Stop; ++it)
{
 //it works like a pointer to masses[i] so it->method();
 double cur_mass = *it;
}

}

If you have a system with 1000 particles the information you will need to save/enter will be the same whether you have individual particles, arrays of attributes or a container of particles.

Who said you won't have to worry about out of bounds checking when using vectors? To my knowledge the big advantage of using vectors has to do with memory handling and keeping track of things like size, empty, etc, not bounds checking. Having said that, if you are going to be resizing the system from 1000 to 5000 or 10000 or whatever, then using a vector might allow a smoother "scaling up/down" of the system than using arrays.

IMHO, using iterators instead of indexes to control looping through a container is 6 of one and half an dozen of the other.

Using classes you can sometimes automate things a little bit. For example, if a change in one attribute automatically changes other attributes you can create a method to change all the attributes and just call that one method instead of manually figuring in the changes. Or if you want to do a lot of sorting by attributes, etc, you can often write a little more code early on to limit the code you need to write later, etc.

Using classes does promote the possibility of reuse in a later project, particularly if the classes are declared in a header file as opposed to directly within the program, but that might not be that important.

All in all, I think you can use whichever style, parallel arrays/vectors or arrays/vectors of objects, that you feel most comfortable with, unless, form your point of you you can make a major benefit out of what appears to be minimal potential benefits.

Indeed, the information to be stored is the same regardless of whether it's in an array or in an object of a class. I guess it was my misunderstanding that vectors are setup such that they prevent bounds from being exceeded.

It is true that I need flexibility to scale up/down the system easily, so if this is an advantage of vectors it would make sense in that case for me to make use of them.

I do want to setup my environment such that there is a possibility of adding attributes in the future, so from that perspective it seems that using a class might not be a bad idea.

The issue that I really have with arrays now I guess, is that when two particles collide in my simulations, they are reduced to one. Since the particles are basically indexed by the row number in the array, this means eliminating a row, which means shifting a whole lot of data up and down the array. I am worried that this might be a weak way of programming as lead to simple errors. With a unique identifier to the objects which is not linked to the row number in the array e.g., a pointer to the object, it is my understanding that I would be eliminating this source of error.

I guess I need to think more carefully about the relation of this aspect of the simulation to the rest too.

Thanks for your input,

Kartik

I do want to setup my environment such that there is a possibility of adding attributes in the future, so from that perspective it seems that using a class might not be a bad idea.

You should probably spring for some type of object in this case. Though, you might find it more suitable to use a struct for your code. Struct objects don't need a constructor (though you can give them one) and all of their members are public, so access is simpler. Of course, you can specify a class with no constructor and all public members, but what would be the point?

It is true that I need flexibility to scale up/down the system easily, so if this is an advantage of vectors it would make sense in that case for me to make use of them.
...
The issue that I really have with arrays now I guess, is that when two particles collide in my simulations, they are reduced to one. Since the particles are basically indexed by the row number in the array, this means eliminating a row, which means shifting a whole lot of data up and down the array. I am worried that this might be a weak way of programming as lead to simple errors. With a unique identifier to the objects which is not linked to the row number in the array e.g., a pointer to the object, it is my understanding that I would be eliminating this source of error.

Vectors would indeed allow you a great deal of flexiblility in dynamic expansion. However, it is not efficient to add or remove items from the middle of a vector. If you remove an object from the middle of a vector, it has to shift all of the items after the removal by 1 place. This is expensive, especially when the items are large (like user defined objects) Having a vector of object pointers is good, because any necessary shift will only have to move 4 or 8 bytes ( for a 32 or 64 bit address pointer ).

If you are not concerned about the ordering of your vector ( the items don't need to be sorted, or their order is otherwise arbitrary ), you can do an nice trick with vectors. Suppose you need to remove item i in the vector. Simply swap item i with the item at the end of the list, then pop off the back of the list. This works perfectly with pointers, because it is very fast to swap small items. This method might work well for you in merging colliding particles.

Good luck, and keep us posted on your progress!

Well I did ask :) , I had to look-up a lot of the scientific terms and even then some areas are still very complicated.

That's why I attempted to leave out the science in my initial post :)

So you have a statistical model of objects rotating ~in a plane towards a centre so that
the system becomes viscous and slows down.

That's not really true, there's no explicit viscosity in the system. Only simple Keplerian orbits and inelastic collisions.

My concern is that you have a particle that has mass, yet the properties that
are being stored are not representative of a particle object but would be an orbit object.
with code like this it is essential to know what represents meaningful elements to your
calculation.

That's actually not an issue. The representative data is some unit in the simulation. Beyond that, for the physics it doesn't matter, as the model I am using describes the rest.

Fully optimised code will not be suitable for another purpose, but minimal overhead is only going
to be a few seconds to allow code to object orientatede and re-usable. There has to be an awareness
that your time in writing, error proofing and maintaining the code can be the most time critical issue.

Since the simulation is large-scale, the overheads are actually quite important. The more efficiently the code is written, the move cases I can simulate.

Now you can iterate over arrays quickly as a[1000] has a pointer 'a' but it can get tricky
to read what exactly you are doing at each step.
It is often beneficial to take advantage of existing solutions and there will be a lot of common tasks
this makes the use of vectors preferable in my opinion.

With vectors they are built for speed so can overflow if you misuse them.
But what you can easily do with vectors is have a test problem with fewer particles / inputs without
the need to change any code other than change an init() which could load from file.

Yep, I see the advantage of vectors in that sense.

As for efficiency - optimisation is important but often focusing on the overhead of function pointersis missing the key time factors.

- You need to be able to check that what you have coded is what you think that you have asked the computer to do
You want a modular design :
- then you can run the program in stages
- Test a block individually and alter the code at one place easily
- reusable for other purposes

an important class if optimisation is important is clock_t found in <time.h>

This allows a method of timing how long each block takes. When talking about iterators or
a access in order the iterator can be significantly faster it certainly was in the past.

When timing and running C++ code with visual studio you should use Release mode not Debug with
visual studio it can have very dramatic influence on speed.

I'm using Qt at the moment. The code itself is working in C, so in that sense I have a benchmark to test the new code against. Thanks for the timing tip.

In most collision systems, it is checking for collisions that is the time dominant factor, you
need to check what order collisions happen and then recalculate any collisions that might happen as
a consequence of the original collision. It is this area where your design needs to be aware of
solutions that you might want to implement. If your particles are not being treated independently
then a crude approach needs to check 999 * 498 pairs of particles every time a decision changes, yet, it
is likely that not all of the 0.5 million path interactions will need to be done every time there is a collision.

If a zonal system is possible with your statistical method then a pair structure with each
orbit as pointers and G pre-calculated might be appropriate so you could then delete values from the vector

The model in fact considers "closest neighbours" for collision calculations. It's a very simple calculation and involves simply determining if the orbits of two neighbours cross, and if they do so, picking the crossing condition that meets a certain criterion.

The first thing you need to design is your events class what methods do you need?

It is likely that you might need a temporary container of values before deciding which ones to update.

It is also possible to use duplicated versions of values but then you need to carefully manage the sychronisation.

When you describe a run as long are we talking 1 hour, 4 hours or 100 hours?
4 hours can be run without worrying about update shutdowns and finding all the mistakes before the
first run.

The simulations are now quite short, but that is because I am running single cases. It ramps up quite dramatically when I run simulations to determine sensitivity of the results to various input parameters.

//how you might use vectors

#include <vector>
using namespace std; //to avoid std:: before vector
void main()
{

//this could go in a management class
vector<double> masses, eccentricites, semi_major_axes;

int likely_number_of_particles(1000);
//an example of a way to prepare the systrm 
masses.reserve(likely_number_of_particles);


//add a particle this would sit in a function

double mass(100), AU_radius(15), eccentricity(0.9); 
//add to the end
masses.push_back(mass);
semi_major_axes.push_back(AU_radius);
eccentricities(ecentricity);

//this will give a warning could use size_type to avoid
int sz = masses.size();

//now you can use vector like an array

for(int i(0); i < sz; ++i)
{
	double cur_mass = masses[i];
}

//for larger vectors this will be faster
vector<double>::iterator it_stop = masses.end();
for(vector<double>::iterator it(masses.begin()); it != it_Stop; ++it)
{
 //it works like a pointer to masses[i] so it->method();
 double cur_mass = *it;
}

}

Thanks for the code example!

You should probably spring for some type of object in this case. Though, you might find it more suitable to use a struct for your code. Struct objects don't need a constructor (though you can give them one) and all of their members are public, so access is simpler. Of course, you can specify a class with no constructor and all public members, but what would be the point?

There are some physical parameters that I need to compute that should remain private (they serve as just system checks) so in that sense I guess a class is most appropriate.

Vectors would indeed allow you a great deal of flexiblility in dynamic expansion. However, it is not efficient to add or remove items from the middle of a vector. If you remove an object from the middle of a vector, it has to shift all of the items after the removal by 1 place. This is expensive, especially when the items are large (like user defined objects) Having a vector of object pointers is good, because any necessary shift will only have to move 4 or 8 bytes ( for a 32 or 64 bit address pointer ).

If you are not concerned about the ordering of your vector ( the items don't need to be sorted, or their order is otherwise arbitrary ), you can do an nice trick with vectors. Suppose you need to remove item i in the vector. Simply swap item i with the item at the end of the list, then pop off the back of the list. This works perfectly with pointers, because it is very fast to swap small items. This method might work well for you in merging colliding particles.

Good luck, and keep us posted on your progress!

That's the main problem I have with using arrays/vectors, that the ordering does matter and then removing a row is an expensive operation. That's why I thought a vector/array of points to objects would be more efficient, because in essence the ordering doesn't matter then indeed. I guess I'll try and go about setting it up that way, generating a set of objects and tracking them using a vector of pointers to them.

I'm not quite sure how to go about this though. For instance, if my class is called Particle, how do I go about setting up firstly 1000 objects of this class, and secondly pointers to each of the objects in an array/vector?

Thanks for the input,

Kartik

I'm not quite sure how to go about this though. For instance, if my class is called Particle, how do I go about setting up firstly 1000 objects of this class, and secondly pointers to each of the objects in an array/vector?

Thanks for the input,

Kartik

You can do this quite easily with classes by using dynamic memory allocation ( the new keyword in c++. So:

class Particle{
       // Internals
      public:
        Particle( double param0, double param1 );  // However you want to work it
};

int main(){
    vector<Particle*> particles;
    for( int i=0; i<1000; i++ )
        particles.push_back( new Particle( param0, param1 ) );
    return 0;
}

You could, of course, use a temporary pointer as a midway point if you need to do something with the particle before you add it to the collection. So:

int main(){
    vector<Particle*> particles;
    Particle* part;
    for( int i=0; i<1000; i++ ){
        part = new Particle( param0, param1 );
        // do stuff with particle
        particles.push_back( part );
    }
    return 0;
}

Either way, it should not be too difficult to build your collection of particles. The only thing you will need to be carefull of is clean up. Since your collection contains pointers instead of the actual objects, you have to explicitly delete each particle in the list to free the allocated memory. So:

int main(){
    vector<Particle*> particles;
    // do a bunch of stuff including adding particles to the container
    for( unsigned int i=0; i<particles.size(); i++ )
        delete particles[i];
    return 0;
}

Hope that helps!

You should probably spring for some type of object in this case. Though, you might find it more suitable to use a struct for your code. Struct objects don't need a constructor (though you can give them one) and all of their members are public, so access is simpler. Of course, you can specify a class with no constructor and all public members, but what would be the point?


Vectors would indeed allow you a great deal of flexiblility in dynamic expansion. However, it is not efficient to add or remove items from the middle of a vector. If you remove an object from the middle of a vector, it has to shift all of the items after the removal by 1 place. This is expensive, especially when the items are large (like user defined objects) Having a vector of object pointers is good, because any necessary shift will only have to move 4 or 8 bytes ( for a 32 or 64 bit address pointer ).

If you are not concerned about the ordering of your vector ( the items don't need to be sorted, or their order is otherwise arbitrary ), you can do an nice trick with vectors. Suppose you need to remove item i in the vector. Simply swap item i with the item at the end of the list, then pop off the back of the list. This works perfectly with pointers, because it is very fast to swap small items. This method might work well for you in merging colliding particles.

Good luck, and keep us posted on your progress!

You can do this quite easily with classes by using dynamic memory allocation ( the new keyword in c++. So:

class Particle{
       // Internals
      public:
        Particle( double param0, double param1 );  // However you want to work it
};

int main(){
    vector<Particle*> particles;
    for( int i=0; i<1000; i++ )
        particles.push_back( new Particle( param0, param1 ) );
    return 0;
}

You could, of course, use a temporary pointer as a midway point if you need to do something with the particle before you add it to the collection. So:

int main(){
    vector<Particle*> particles;
    Particle* part;
    for( int i=0; i<1000; i++ ){
        part = new Particle( param0, param1 );
        // do stuff with particle
        particles.push_back( part );
    }
    return 0;
}

Either way, it should not be too difficult to build your collection of particles. The only thing you will need to be carefull of is clean up. Since your collection contains pointers instead of the actual objects, you have to explicitly delete each particle in the list to free the allocated memory. So:

int main(){
    vector<Particle*> particles;
    // do a bunch of stuff including adding particles to the container
    for( unsigned int i=0; i<particles.size(); i++ )
        delete particles[i];
    return 0;
}

Hope that helps!

Thanks a lot! :)

Is the functionality of the code example you've provided with me essentially doing the same as the following?

#include <iostream>
 
 class MyClass
 {
 public:
     MyClass() { 
        itsAge = 1; 
        itsWeight=5; 
     } 
     ~MyClass() {}                          
     int GetAge() const { return itsAge; }
     int GetWeight() const { return itsWeight; }
     void SetAge(int age) { itsAge = age; }
 
 private:
     int itsAge;
     int itsWeight;
 };
 
 int main()
 {
     MyClass * myObject[50];
     int i;
     MyClass * objectPointer;
     for (i = 0; i < 50; i++)
     {
         objectPointer = new MyClass;
         objectPointer->SetAge(2*i +1);
         myObject[i] = objectPointer;
     }
 
     for (i = 0; i < 50; i++)
         std::cout << "#" << i+1 << ": " << myObject[i]->GetAge() << std::endl;

 
     for (i = 0; i < 50; i++)
     {
         delete myObject[i];
         myObject[i] = NULL;
     }
 
     return 0;
 }

Got that code when I googled "array of pointers to objects" (http://www.java2s.com/Tutorial/Cpp/0180__Class/Anarrayofpointerstoobjects.htm).

Thanks!

Kartik

EDIT: Additionally, since the number of objects required is declared already before runtime, is dynamic allocation necessary? My understanding is that dynamic allocation requires more overheads right?

Also, once I declare objects, they all acquire properties through the constructor, which I then have to sort in ascending/descending order, based on the numerical values of the properties. Is there an easy way of sorting in this manner?

An alternative to deletion of elements when using vectors/arrays is to add a member variable to the class indicating whether an element of the array/vector that was "alive" at one point in the program is still "alive" at the time it is "evaluated".

As you are probably aware, if frequent additions/deletions are a desired then a list or an ordered list may be more "effective" than an array. Lists however "suffer" from "access" problems. As a sort of a compromise, trees can be developed that have access speeds between arrays and lists and flexibility in terms of additions and deletions that is similar to lists. Each node in a list (or tree) has the added memory requirement of one or more pointers as member variables, but, as they say, memory is cheap these days.

Why all the quotes in my discussion? Because, everything is debatable. In the end you have to decide which of the available containers (arrays, vectors, lists, trees, etc) is most suitable to you an to your program.

>>sort in ascending/descending order, based on the numerical values of the properties. Is there an easy way of sorting in this manner?

Once you've established criteria on how to sort, it usually isn't too hard to write code to do so. There is a standard sort() function, but the objects to be sorted must have the appropriate overloaded comparison operator for sort() to work.

>>since the number of objects required is declared already before runtime, is dynamic allocation necessary? My understanding is that dynamic allocation requires more overheads right?

You are going to need memory for the objects somehow. Whether you get the memory using dynamic memory or static memory is immaterial in terms of the amount of memory you are going to need. Of course, when the total amount of memory required exceeds the amount of memory available on the stack then you have to use the heap (accessing it using dynamic memory). There is more overhead in setting things up using new, because of each call to new during the set up; but once the information is all in place the ability to use the information isn't affected (to my knowledge anyway) by whether the information is on the stack or on the heap.

Is the functionality of the code example you've provided with me essentially doing the same as the following?
someCode{}
Got that code when I googled "array of pointers to objects" ( http://www.java2s.com/Tutorial/Cpp/0180__Class/Anarrayofpointerstoobjects.htm ).

Yes, that is functionally equivalent. However, the array in this case is not dynamic at all.

Additionally, since the number of objects required is declared already before runtime, is dynamic allocation necessary? My understanding is that dynamic allocation requires more overheads right?

Doing multiple dynamic allocations ( repeated calls to the new keyword for single objects ) can introduce an overhead. However, using dynamic allocation lets you avoid the very real possibility of overflowing the stack. I would highly suggest that you use dynamic allocation that is dependent on a variable that is specified at run-time. In my opinion, it is always better to take a little bit more time to make a program flexible, because it is likely that it will need to be extended at some point in its life. For small objects on the order of 1000 to 10000 instances, I wouldn't worry about using dynamic allocation. The only time when you really take a hit on dynamic allocation is when objects are getting dynamically allocated and freed frequently within a region of code ( say, in a for loop ).

Also, once I declare objects, they all acquire properties through the constructor, which I then have to sort in ascending/descending order, based on the numerical values of the properties. Is there an easy way of sorting in this manner?

The standard template library allows you to sort a vector ( and many other containers ) using a user defined sort function. This is very handy, and the stl uses a very efficient sort method ( introsort with O( nlogn ) ). Have a look at this for a brief example/discussion of the sort method

You're getting closer!

Thanks for all the feedback!

Been busy last couple of days trying to implement it all. I'll get back with an update on where I am tomorrow when I can finish up a few more things.

Thanks a lot for all your help!

Regards,

Kartik

Thanks for all the feedback!

Been busy last couple of days trying to implement it all. I'll get back with an update on where I am tomorrow when I can finish up a few more things.

Thanks a lot for all your help!

Regards,

Kartik

I've managed to get my preliminary code working! Got a vector of objects pointers now and I am able to work with the vector in my simulation. Also managed to implement the sort function, though I discovered that you need a workaround to use it if you're using a sort function that's defined in a class. I don't like the workaround, but for now it's working (posted another thread about the workaround, but got no response).

Maybe as I get more savvy with C++ I can figure out a way to code this more elegantly.

Anyway, thanks a lot to all who provided me with feedback here! Very much appreciated :)

Got lots of other questions, but I'll just post them up in separate threads. This one is case closed now I believe :)

Cheers,

Kartik

I've managed to get my preliminary code working! Got a vector of objects pointers now and I am able to work with the vector in my simulation. Also managed to implement the sort function, though I discovered that you need a workaround to use it if you're using a sort function that's defined in a class. I don't like the workaround, but for now it's working (posted another thread about the workaround, but got no response).

Maybe as I get more savvy with C++ I can figure out a way to code this more elegantly.

Anyway, thanks a lot to all who provided me with feedback here! Very much appreciated :)

Got lots of other questions, but I'll just post them up in separate threads. This one is case closed now I believe :)

Cheers,

Kartik

I'm curious as to what the work around was and where you posted your question.

I'm curious as to what the work around was and where you posted your question.

Ah my bad, I thought I had posted it, but I actually posted a question regarding the use of the accumulate function (http://www.daniweb.com/forums/thread261682.html; if you have feedback regarding this question I'd be very grateful :) ).

The workaround I found for using the sort function is given here:
http://bytes.com/topic/c/answers/525611-problems-stl-sorting-using-member-functions

It works fine, but now I have this inelegant struct in the middle of one of my header files. My understanding is that I can't use sort the way I want because the function I want to use belongs to a class and is therefore not static.

Maybe there's an easier way to go about sorting?

Thanks,

Kartik

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.