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

Not sure about using vectors to store object of different Types



  • Hi,

    What I have right now is a simple inheritance structure with classes water, juice and tea that all inherit from the drink class. For example in the main method i created a few waters, juices and teas, each with their specific fields that only they have. Then I stored them in a vector that holds drink, but when I iterate through the vector, I would lose the properties and methods that only apply to the sub classes, is there a way to get around this apart from making lots of arrays for each class and iterating through them, as I would want to add many different other types of drinks.

    Thanks



  • This a better topic for the C++ specific forum, rather than the Qt framework forum...but for the record, this is basic OO programming in C++ knowledge...I suggest reading a book on how C++ implements inheritance and polymorphism...your generic vector will work fine if it stores pointers to the generic base class, and you have defined the sublclasses properly.



  • std::vector<std::any> beverages;
    std::vector<std::variant<Gin, Whiskey, Vodka>> beverages;
    


  • You create generic methods in the base class. These methods should be virtual. Then in each derived class you define the corresponding method and override the base class method. The trick is keeping the interface generic. So lets say you have a method called ingredients() which returns a list of ingredients. Then you have a base class method:

    class drink
    {
    ...
    virtual QStringList ingredients()=0;  // tells compiler it is pure virtual
    ...
    };
    
    class tequila : public drink
    {
    ...
    QStringList ingredients() override 
    {
      return QStringList();
    }
    ...
    };
    

    The syntax may not be exact, but you get the idea. So in your list you only deal with drink:
    **Edit:**Like @jsulm pointed out, it needs pointers. DOH!

    QVector<drink*> drinks;
    drinks.push_back(new tequila());
    ...
    for(auto d: drinks){
      qInfo() << d->ingredients();  //  calls function that is specific to actual object
    }
    

  • Lifetime Qt Champion

    @fcarney For this to work you have to use pointers:

    QVector<drink*> drinks;
    

Log in to reply