I know that if there is an abstract class (for example: Account) and heirs of an abstract class (PrivelegeAccount, SavingAccount), then we can use our heirs through a pointer to the parent class (Account *).

So the task: We must have a dynamic array of accounts of different types. How to do this and is it possible to create it through vector?

Sincerely.

  • So declare a vector with the type Account *, and it will be possible to place objects inheritances into it, but you can use only those methods that are available in the parent (here I do not consider the explicit cast to the ancestor class). Similar examples are in any textbook on the PLO, you can see. - Evgenii Izhboldin
  • not, so does not work, I tried - Student
  • keep pointers (simple or smart) - AR Hovsepyan
  • @Evgenii Izhboldin, even if you really want to, cannot still realize a vector with the Account type, since it’s about the fact that this is an abstract class - AR Hovsepyan
  • @AR Hovsepyan, well, I meant pointers - Evgenii Izhboldin

1 answer 1

You should store items in a vector index. Better use a smart pointer. Sort of:

struct Account { virtual ~Account() = default; // Пожалуй все-таки не стоит забывать про виртуальный деструктор virtual std::string GetMessage() = 0; }; struct PrivelegeAccount final: public Account { virtual std::string GetMessage() override final { return "PrivelegeAccount"; } }; typedef std::unique_ptr<Account> AccountPtr; int main() { std::vector<AccountPtr> vector; vector.emplace_back(std::make_unique<PrivelegeAccount>()); for (const auto& account : vector) std::cout << account->GetMessage() << std::endl; return 0; } 
  • Firstly, the basic structure is not an abstract class (this is not the point), secondly it is better to fill containers with shared_ptr objects - AR Hovsepyan
  • one
    Containers can and should often be filled with unique_ptr. An abstract class can be "logically". But a virtual destructor would not hurt. - KoVadim
  • And why is it necessary to unique_ptr or why is shared_ptr better? - Student
  • @Dim Not necessarily unique_ptr. It all depends on the task. In this example, the pointer has no value. - Jester
  • one
    @Dim shraed_ptr is a pointer with shared ownership. unique_ptr owns the object individually. And, if you do not need to have a pointer to one object in several places in your program, it is more logical to use unque_ptr, which is at least "easier" than shared_ptr - Jester