There is an abstract class "Organism". It is inherited by 2 classes: "Animals" and "Plants"

How can you store objects of the classes "Animals" and "Plants" in 1 array \ vector \ something else

  • Whatever ... If these classes do not have any specific features, then there are no specific features in their storage. It is not clear what the problem is. - VTT

3 answers 3

Since this is most likely a computer game, and the Animals and Plants class will be represented as control objects, it is best to use the pattern factory to create the objects themselves, and store their pointers in std :: list or std :: forward_list, since the speed of insertion and deletion (birth, death) of the element will be constant.

  • one
    *Animal and *Plant are different types. Do you suggest that *void lead them? It is wildly dangerous, the best in any store. But it still does not solve a bunch of problems. For example, it’s impossible to make a call to l[1].call() , you can only std::any_cast<Animal>(l[1]).call() - Andrio Skur
  • Here the question is not what to store, but how ... - Mikhailo
 #include <iostream> #include <vector> #include <memory> using namespace std; // Вначале объявим базовый класс class Organism { public: virtual string name() = 0; virtual ~Organism() = default; }; // наследники class Animal : public Organism { public: string name() override { return "Animal"; } }; class Plant: public Organism { public: string name() override { return "Plant"; } }; int main() { // так как на дворе 2018, то пишем на 11 стандарте и используем умные указатели vector<unique_ptr<Organism>> org; // и добавление без new org.push_back(make_unique<Plant>()); org.push_back(make_unique<Animal>()); // а вот здесь объязательно нужно const и &, так как unique_ptr for (const auto& o : org) { // name - виртуальная, поэтому никаких dynamic_cast cout << o->name() << endl; } // и память за нас компилятор освободит. return 0; } 

Perhaps in the future, you will need to replace the unique_ptr with shared_ptr.

Or is it still a school task and the teacher will compile in turbo c ++ 3?

  • I wonder, but what’s wrong, that you decided to put a minus? or difficult decision? (or maybe opponents of school solutions?) - KoVadim
 // Создадим массив и добавим в него одно животное и два растения: std::vector<Organism*> mas; mas.push_back(new Plant); mas.push_back(new Animal); mas.push_back(new Plant); // Узнаем, то, что лежит ли в mas[1] это растение или животное: if (dynamic_cast<Plant*>(mas[1])) { std::cout << "this is Plant" << std::endl; } else if (dynamic_cast<Animal*>(mas[1])) { std::cout << "this is Animal" << std::endl; } else { std::cout << "this is unknown Organism" << std::endl; } // Удаление: for (int i = 0; i < mas.size(); ++i) { delete mas[i]; } mas.clear(); // Если всё было сделано верно, и деструктор класса Organism был объявлен как виртуальный, то delete вызовет правильный деструктор и утечки памяти не будет 
  • the code will not compile - the deletion is a bit incorrectly written. either use the old for view or rewrite the body. - KoVadim
  • Corrected. Used the old view for. - zcorvid