Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can not use abstract class in std::vector?

I have came from those questions:

  • Why can't we declare a std::vector<AbstractClass>?
  • abstract classes in std containers
  • How to store a vector of objects of an abstract class which are given by std::unique_ptr?

They all suggested that I should use pointer or smart pointers instead.

As far as I know, Data are dynamically allocated in std::vector which means that there are pointers internally in the std::vector. So why I can not use abstract classes directly? why I have to use pointers(The one I specified) for pointers(the internally) in order to use abstract classes with std::vector. I know some features like std::vector::resize won't work. However, std::vector::reserve and std::back_inserter will solve the problem.

like image 838
Humam Helfawi Avatar asked Dec 10 '22 16:12

Humam Helfawi


1 Answers

As far as I know, Data are dynamically allocated in std::vector which means that there is pointers internally in the std::vector

That's absolutely right. However, the pointer (actually, one of two pointers in the very common implementation) points to an array of identically-sized elements of type T, not to a single element of T or its subtype. Essentially, the pointer is used to represent an array, not to refer to a class or its subclass.

That is why you need an extra level of indirection - elements of an array T[] are not capable of storing subclasses of T without object slicing.

like image 117
Sergey Kalinichenko Avatar answered Dec 30 '22 15:12

Sergey Kalinichenko