Home > OS >  How would one succinctly compare the values of and call the functions of many derived classes'
How would one succinctly compare the values of and call the functions of many derived classes'

Time:12-10

I have a 2d physics engine that I've been programming in C using SFML; I've implemented a rough collision detection system for all SandboxObjects (the base class for every type of physics object), but I have a dilemma.

I plan to have many different derived classes of SandboxObjects, such as Circles, Rects, and so on, but I want a way to check if the roughHitbox of each SandboxObject collides with another.

When the program starts, it allocates memory for, let's say, 10,000 Circles

int circleCount = 0;//the number of active Circles
constexpr int m_maxNumberOfCircles = 10000;//the greatest number of circles able to be set active
Circle* m_circles = new Circle[m_maxNumberOfCircles];//create an array of circles that aren't active by default

like so.

and every time the user 'spawns' a new Circle, the code runs

(m_circles   circleCount)->setActive();`
circleCount  

Circles that aren't alive essentially do not exist at all; they might have positions and radii, but that info will never be used if that Circle is not active.

Given all this, what I want to do is to loop over all the different arrays of derived classes of SandboxObject because SandboxObject is the base class which implements the rough hitbox stuff, but because there will be many different derived classes, I don't know the best way to go about it.

One approach I did try (with little success) was to have a pointer to a SandboxObject

SandboxObject* m_primaryObjectPointer = nullptr;

this pointer would be null unless there were > 1 SandboxObjects active; with it, I tried using increment and decrement functions that checked if it could point to the next SandboxObject, but I couldn't get that to work properly because a base class pointer to a derived class acts funky. :/

I'm not looking for exact code implementations, just a proven method for working with the base class of many different derived classes.

Let me know if there's anything I should edit in this question or if there's any more info I could provide.

CodePudding user response:

Your problems are caused by your desire to use a polymorphic approach on non-polymorphic containers.

The advantage of a SandboxObject* m_primaryObjectPointer is that it allows you to treat your objects polymorphicaly: m_primaryObjectPointer -> roughtHitBox() will work regardless of the object's real type being Circle, Rectangle, or a Decagon.

But iterating using m_primaryObjectPointer will not work as you expect: this iteration assumes that you iterate over contiguous objects in an array of SandboxObject elements (i.e. the compiler will use the base type's memory layout to compute the next address).

Instead, you may consider iterating over a vector (or an array if you really want to deal with extra memory management hassle) of pointers.

vector<SandboxObject*> universe;  
populate(universe); 
for (auto object:unviverse) {
    if (object->isActive()) {
        auto hb = object -> roughtHitBox(); 
        // do something with that hitbox
    }
}

Now managing the objects in the universe can be painful as well. You may therefore consider using smart pointers instead:

vector<shared_ptr<SandboxObject>> universe;  

(little demo)

CodePudding user response:

It's hard to answer this without knowing the requirements but you could have sandbox maintain two vectors of active and inactive objects, and use unique_ptrs of the base class for memory management.

Some code below:

#include <vector>
#include <memory>
#include <iostream>

class sandbox_object {
public:
    virtual void do_something() = 0;
};

class circle : public sandbox_object {
private:
    float x_, y_, radius_;
public:
    circle(float x, float y, float r) :
        x_(x), y_(y), radius_(r)
    {}

    void do_something() override {
        std::cout << "i'm a circle.\n";
    }
};

class triangle : public sandbox_object {
private:
    float x1_, y1_, x2_, y2_, x3_, y3_;
public:
    triangle( float x1, float y1, float x2, float y2, float x3, float y3) :
        x1_(x1), y1_(y1), x2_(x2), y2_(y2), x3_(x3), y3_(y3)
    {}

    void do_something() override {
        std::cout << "i'm a triangle.\n";
    }
};

class sandbox {
    using sandbox_iterator = std::vector<std::unique_ptr<sandbox_object>>::iterator;
private:
    std::vector<std::unique_ptr<sandbox_object>> active_objects_;
    std::vector<std::unique_ptr<sandbox_object>> inactive_objects_;
public:
    void insert_circle(float x, float y, float r) {
        active_objects_.push_back( std::make_unique<circle>(x, y, r) );
    }

    void insert_triangle(float x1, float y1, float x2, float y2, float x3, float y3) {
        active_objects_.push_back( std::make_unique<triangle>(x1,y1,x2,y2,x3,y3));
    }

    sandbox_iterator active_objs_begin() {
        return active_objects_.begin();
    }

    sandbox_iterator active_objs_end() {
        return active_objects_.end();
    }

    void make_inactive(sandbox_iterator iter) {
        std::unique_ptr<sandbox_object> obj = std::move(*iter);
        active_objects_.erase(iter);
        inactive_objects_.push_back(std::move(obj));
    }

};

int main() {
    sandbox sb;

    sb.insert_circle(10.0f, 10.0f, 2.0f);
    sb.insert_triangle(1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 1.0f);
    sb.insert_circle(1.0f, 6.0f, 4.0f);

    sb.make_inactive(sb.active_objs_begin());
    (*sb.active_objs_begin())->do_something(); // this should be the triangle...

    return 0;
}
  • Related