C++: Instances of the same class

Asked

Viewed 58 times

1

I have in a project a class Collision, and to make detection more efficient, wanted to have access to all instances (objects) of that same class. Is there any easy way to do this?

Edit 1
I did this: I created a class called world, which stores all objects and collisions, where I have the method isColliding, which checks the collision between an object and all other objects, or between two objects.

  • 3

    You can save an entire class instance array right away by creating the new object in the constructor and removing it from the vector by deconstructing the object. Be aware who compare all instantiated objects may not be the best solution, this alternative solution you proposed is correct, but it can cost a lot of processing and slow down the game

  • 3

    I thought of something of this suit. A container static (e. g., vector, set, map or unordered_set) with pointers for each instance. Constructors and destructors respectively add or remove elements from the collection.

  • 2

    Post as response.

  • 1

    @Jeffersonquesado , if I do not check with all objects, as I will analyze the collision?

  • @moustache typing on mobile is costly. I’m with another issue in draft, ending that I go back to that

  • @Felipebirth segmentation by position/classes of Apollo; Mario’s red turtles don’t need to know they have ground, they only move between fixed points, so we don’t need to bump them into the ground. In the future answer I will go into more detail

Show 1 more comment

1 answer

1


Not to be without record of reply, I answer here what has already been answered in the comments and made by the OP: create a container with pointer for all created objects, inserted at the time of construction. I suggest using a binary tree (std::set), to reduce complexity:

class Collision;

std::set<Collision> world;

class Collision {
public:
    Collision() {
        world.insert(this);
    }

    ~Collision() {
        world.erase(world.find(this));
    }
}

That way you can find all the Collision instantiated in your program.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.