Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Base and derived class that use different types of objects



  • I would like to design a base class that I will use to manage some base objects (for base I mean they have no GUI elements); and I want to create a derived class from that base class that will use some derived objects from the base objects. Let me explain in code...
    @class baseObject;
    class derivedObject : public baseObject;

    class baseClass{
    QList<baseObject> * objects;

    void someMethod(baseObject * obj);
    

    }

    class derivedClass : public baseClass{
    QList<derivedObject> * objects;

    void someMethod(derivedObject * obj);
    

    }@

    What bothers me is that QList thing because I want to use objects of different type in the base and derived classes. The baseObject and derivedObject will use the same methods to interact with the object, so they are code-call compatible; the difference is that the derivedObject will make use of widgets and draw a GUI. The same for the baseClass and abstractClass.

    I have never had to deal with this before and I have no idea how to proceed. Actually, something similar already bothered me before and I was suggested to create a GUI object that internally uses the non-GUI object (so instead of deriving the derivedClass, it should be a class on its own and have internally a baseClass object); but it is not applicable in this case since the baseClass and derivedClass use objects of different type.

    Any suggestions ?


  • Moderators

    You are working on object pointers, so it will work. You don't need to define "objects" member in derivedClass: just use the member from baseClass and cast your pointers if necessary.



  • You mean using static_cast and dynamic_cast ? I never worked with these and I'm pretty sure I have no idea what am I doing at first :D I'll have a look at some guides, thanks ;)

    Now what about if the objects type is totally different, instead of derivedObject from baseObject let's suppose I have totally different objects which are incompatible for a cast... is there any way for working with that as well? I've heard about using void* pointers which are "compatible" with any other pointer type, but I haven't used these either and I don't know what am I talking about...


  • Moderators

    Same thing with void * pointers: they need casting. For classes derived from QObject, there is a better alternative: qobject_cast. Or you could venture into the land of templates, where dragons live, but possibilities are endless.

    This is quite an abstract topic. I suggest you simply try it out on some project you devise and then post more specific questions when something is unclear. In many cases, the compiler will correct you.



  • Ok, I got it. Thank you for your help ;)


Log in to reply