Search code examples
c++inheritancebox2d

Derived class of b2Body or class containing a b2Body object?


I currently have a class 'WorldObject' which contains a pointer to its b2Body, and several methods and variables.

But wouldnt it be smarter to make WorldObject a derived class of the b2Body?

What is the general approach to that sort of things? To Always create a derived class of the most important object in the class, or to just create a new one and make everything attributes?

What are the pros and cons of these possibilities?

Thank you.


Solution

  • It is usually better to do composition and not to overuse inheritance.

    Note also that you usually create a body calling b2World::CreateBody() and that returns a b2Body*, and with inheritance that would not be possible.

    To avoid the problems with the lifetime of the inner b2Body* you can use smart pointers. I use this definition:

    class BodyDeleter
    {
    public:
        BodyDeleter()
            :m_world(NULL)
        {}
        BodyDeleter(b2World *world)
            :m_world(world)
        {}
        void operator()(b2Body *body)
        {
            if (m_world)
                m_world->DestroyBody(body);
        }
    private:
        b2World *m_world;
    };
    
    typedef std::unique_ptr<b2Body, BodyDeleter> b2BodyPtr;
    

    Then, in my WorldObject:

    class WorldObject
    {
    protected:
        WorldObject(b2World *world)
        :m_body(NULL, m_world)
        {}
       b2BodyPtr m_body;
    };
    

    And then, in the actual subclasses of WorldObject:

    class SpaceShip : public WorldObject
    {
    public:
        SpaceShip(b2World *world)
        :WorldObject(world)
        {
            //initialize bodydef and whatever
            m_body.reset(world->CreateBody(...));
        }
    };