Search code examples
c++queuederived-classstdarray

Can I derive a class from `std::array`?


In general standard container classes are not intended to be derived from, e.g. they have non-virtual destructors.

However, I noticed that std::array does not define a destructor at all (at least in the GNU library).

Does it mean std::array is safe to derive from?

I do not intend to overload any of its member functions, just add a few more (mainly to use it as a fixed size queue).


Solution

  • It is safe to derive from a class with non-virtual destructor non-publicly. It is only public inheritance that is potentially unsafe.

    std::array has a destructor regardless of whether one has been declared. All classes have destructors. It is always UB to delete an object through a base class pointer if the base class destructor isn't virtual. std::array is not different in that regard.