new/delete operators on class

I am making a shooter game where there will be lots of bullets. I know there is a way to use the new and delete operators on the bullet class's constructor to create new objects, then get rid of them when their done, but, how would I do that? Also, how would I keep track of all the bullets (for updating/collision detection etc)? Any help would be great!
Hmm... you could use new and delete for keeping track of those bullets by making an array, but I would suggest something that could store an arbitrary number of bullets, if necessary. In other words, I'd suggest a vector. :)

http://www.cplusplus.com/reference/stl/vector/

I hope the above link will help. I'd suggest reserving() about 1.5 times the average number of bullets you would expect on the screen at any one time, just for performance reasons.

Actually, I'd suggest the average number of bullets on the screen at one time plus two standard deviations of that variable, but...

-Albatross
Last edited on
I think I understand. I don't know how I would implement a vector though. However, after I create my vector, I would use the operator[] thing to access the members of the vector, which would be instances of my bullet class. My bullet class goes something like this:
1
2
3
4
5
6
7
8
class bullet {
    public:
    int x, y, dir;
    bool is_shot;
    int sx, sy;  //for displaying purposes
    void change_xy();
    void check_hit();
};

How would I declare a vector containing the above class? I understand the basics of templates, but I'm not great with them.
I never said you'd have to implement a vector... ;)

Assuming that you've already #include/*d*/ <vector> , all you need to do to make a vector of bullets is:
std::vector<bullet> vector_name;

From there, you have several member functions and operators which may be of interest:
http://www.cplusplus.com/reference/stl/vector/push_back/
http://www.cplusplus.com/reference/stl/vector/erase/
http://www.cplusplus.com/reference/stl/vector/reserve/
http://www.cplusplus.com/reference/stl/vector/operator[]/
http://www.cplusplus.com/reference/stl/vector/size/

Good luck!

-Albatross
Adding to what Alatross has said, you need to check out the Flyweight pattern. The last thing you want to do is to start treating each bullet as an object that you have to deal with directly as you could have thousands.
Thanks! Those pages are really helpful. The Flyweight pattern also looks very useful!
Topic archived. No new replies allowed.