0

It is possible in C++ to declare such class:

class A : public std::vector<A>
{
public:
    A() = default;
    ~A() = default;
}

Ok, it is bad to inherit from STL containers, it is bad to hide non-virtual destructor.

But is there any purpose of classes like this? What it can be used for?

vladon
  • 8,158
  • 2
  • 47
  • 91
  • 1
    Recommended reading: https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern – inetknght Jan 04 '16 at 21:04
  • Also see: http://stackoverflow.com/questions/4353203/thou-shalt-not-inherit-from-stdvector – NathanOliver Jan 04 '16 at 21:06
  • 3
    @inetknght, in order to get the benefit of CRTP, the base needs to be aware of it. `std::vector<>` is certainly not. – SergeyA Jan 04 '16 at 21:07
  • Sure, absolutely. But OP asked *"is there any purpose of classes like this?"* which I interpreted to mean *"is there any purpose of a curiously recurring template pattern?"* – inetknght Jan 04 '16 at 21:08

2 Answers2

2

Since destructor of std::vector<> is non-virtual, there is no point in making destructor of derived class virtual - your class will not behave polymorphically when base is used.

However, there might be some benefit in using non-polymorphic inheritance, for instance, by overriding some vector functions.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Sorry, I removed `virtual`. – vladon Jan 04 '16 at 21:04
  • But what the reason to declare `A` as inherited from vector of `A`? What is the profit? Just for overriding? – vladon Jan 04 '16 at 21:07
  • 1
    @vladon, I do not really now. It looks syntaxically similar to CRTP (see one of the comments), but it is not, since std::vector is not CRTP-aware. – SergeyA Jan 04 '16 at 21:08
2

Things become miserable as soon as the class is recognized as a base class, only (due to an operator or a function taking the base class). Just do not do it. A sample try for a modifying/extending attempt might be std::string - there is none.

vsoftco
  • 55,410
  • 12
  • 139
  • 252