-2

I'm having a problem with using C++ inheritance and was wondering if anybody could help.

I want to declare a class List derived from std::vector<Entry>, where the class Entry is a nested class declared inside the List class (to limit access and clear class naming).

I've tried this following code:

class List : public std::vector<List::Entry> {
  class Entry { /* ... */ };
}

But an error occurs in this code:

No member named 'Entry' in 'List'

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
WON
  • 79
  • 1
  • 9
  • 4
    why inherit publicly from `std::vector` in the first place? – 463035818_is_not_a_number May 24 '22 at 15:30
  • 4
    Consider having a `std::vector` as a *member* of `List` instead. – Bob__ May 24 '22 at 15:33
  • @463035818_is_not_a_number I need several custom member functions in addition to '''std::vector''' such as build() and update() – WON May 24 '22 at 15:33
  • @Bob__ thanks for comment. but it is too boring to implement wrapper of vector members (such as size, push_back) compared to inherit vector class. is there any good way? – WON May 24 '22 at 15:36
  • 3
    See here why it's usually a bad idea to inherit from a stl container: https://stackoverflow.com/questions/2034916/is-it-okay-to-inherit-implementation-from-stl-containers-rather-than-delegate. – wohlstad May 24 '22 at 15:40
  • 2
    boring? um, there isnt many nicer things than boring simple code. – 463035818_is_not_a_number May 24 '22 at 15:41
  • 4
    @WON Publicly inheriting from standard containers to extend them is generally not recommended. These types are not polymorphic and doing so can easily introduce very hard to find bugs. – François Andrieux May 24 '22 at 15:42
  • 4
    the answer to your question is: No you cannot inherit from the class before you defined it. Though, https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem, if you ask for the actual issue you are trying to solve (for which you think inheriting from a vector of elements of a nested class would be the solution) I suppose better solutions can be found – 463035818_is_not_a_number May 24 '22 at 15:43
  • 2
    While boring, you'll gain control of the public interface of *your* class. – Bob__ May 24 '22 at 15:44
  • Thanks for the advice! I now know that inheritance of STL containers is dangerous. I'll follow Bob's comment. – WON May 24 '22 at 15:53

0 Answers0