I thought I could make my animation run faster by having drawing operations done in one objects and to eliminate get and set methods with using pointers. So I had:
datatypes.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
struct pellet
{
int the_type;
float x, y, buf //buf is there so the size of both structs is the same
unsignedlong id;
}
struct explosion
{
int the_type;
float x, y, seq
unsignedlong id;
}
union objects_on_scr
{
struct pellet p;
struct explosion e;
}
fireworks.cpp: Yea I have problems being consistent with names. whatever
1 2 3 4 5 6 7 8 9 10
#include "datatypes.h"
...
void fireworks::launch()
{
struct pellet *a = (struct pellet*) malloc(sizeof(struct pellet));
a.the_type=1;
/* set pellet a data */
drawer->pass_pellet_info(a);
}
...
if it matters in fireworks.h/.cpp and explosion.h/.cpp I was using a linked list but in sprite_handler I used vector. Inconsistent I know. How I tried to handle memory leaks was like this:
id is set with the system clock Pellet.id = clock();
before a node gets deleted in fireworks.cpp I call delete_object:
1 2 3 4 5 6 7 8 9
void renew(struct pellet*& a)
{
struct b = a;
if //delete condition
{
drawer->delete_object(a->id);
pop(a);
}
}
I tried to do all this initially with polymorphism (abstract base class) but the complexity got away from me so I went to something more familiar. I can retry.
Just a couple suggestions:
_ You are programming in c++, then use the c++ facilities. If you want a list of circles, simply do list<circle> a_list_of_circles; (reuse code that works)
_ The idea of methods is to use/modify the state of the object. If they aren't doing that, then they shouldn't be methods.
_ Don't use dynamic allocation unless necessary.
Bjarne Stroustrup wrote:
Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient.
_ The constructor is invoked at the creation of the object. Use it to put your object in a valid state.
I rewrote it with a vector and only one object class and it works fine now. Thanks.
Would using an base abstract class help if you are dealing with different but similar classes? I made a game that had basically a bunch of bad guys with a bunch of weapons and the game was unstable. I used vectors. Sometimes it would work fine other times it would crash. The biggest problem I think was the collision detection class I wrote for it which made its own datatype and stored essential info on every on-screen object. I had to be careful how often I fired the shotgun weapon lest I crash the program.
I wouldn't bother running it on my old macbook with only 2Gs of RAM D:
I'm always on the look out for ways to conserve RAM. I personally think its always better to conserve memory even at the expense of processor usage (although the 2 aren't mutually exclusive)