mardi 26 janvier 2021

Should i use dynamic_cast here?

Well, i have next code:

#include <type_traits>
#include <iostream>
#include <string>
#include <list>
#include <functional>

class base_main
{
public:
    virtual ~base_main()
    {
    }
    // some methods
};

class base_1 : virtual public base_main
{
    // some methods
};

class base_2 : virtual public base_main
{
    // some methods
};

class base_3 : virtual public base_main
{
    // some methods
};

class object : public base_1, public base_2, public base_3
{
    // some methods
};

// in other *hpp file

class object_controller_listener
{
public:
    virtual void object_created( base_main* o )
    {
        // well, i want to work only with base_1 and base_2 interfaces, but not with base_3, and also i don't want to know something about object class in this *hpp
        // is it good code design?
        auto* xxx = dynamic_cast<base_1*>( o );
    }
};

class objects_controller
{
    void create()
    {
        std::unique_ptr<object> obj;

        // ...
        
        for( auto listener : m_listeners )
            listener->object_created( obj.get()  );
    }

    std::list<object_controller_listener*> m_listeners;
};

int main()
{

}

The question is - how can i work only with base_1 and base_2 interfaces? Should i create two separate listeners for them, and send two events in create() function, or should i use dynamic_cast for downcasting and send only one event in create() function? Is this good code design or is this feels like code smell?

UPD:

For example: base_1 - is render_base class, which contains render data, and have functions for set and get this data base_2 - collider base class which contains collider data, and have functions for set and get this data base_3 is physic base class and object is inheritance of all this classes. And when i want work only with render class i use create event which send only render_base class to the render_system, which works only with renders objects and truly use polymorphism. But if i want in some other place work with collider and physic objects, without knowledge about render - how can i use polymorphism here in base classes?

Aucun commentaire:

Enregistrer un commentaire