2

Trying to switch from some custom made classes I built to std classes. Just for a start, I am trying to derive from std::vector.

#include <vector>

template < class DATA_T >
class CArray : public std::vector < DATA_T >
{
public:
    DATA_T* Create (size_t length) {
        reserve (length);
        return data;
    }
};

"reserve": Identifier not found
"data":  Identifier not found

As far as I could see, both are public members of std::vector.

What is my mistake?

Razzupaltuff
  • 2,250
  • 2
  • 21
  • 37
  • 2
    The problem is unrelated to `std::vector`, but to deriving from template classes. TL;DR - you need `this->reserve()` and `return this->data();` – Yksisarvinen Nov 04 '21 at 12:55
  • 5
    In addition to the correct duplicate marker, the other thing you're doing wrong is deriving from `std::vector`. It is not meant as a base class, and I strongly suggest you don't do that. – Sebastian Redl Nov 04 '21 at 12:56
  • `reserve` ≠ `resize`. With `this->reserve(length)`, the `this->data()` will refer to zero items if the CArray had zero items before calling `Create`. – Eljay Nov 04 '21 at 13:31
  • @Redl: Why shouldn't I derive vom std::vector? This seems to be a belief as firm as unfounded of C++ programmers. It's a class like others, and if I need a dynamically allocated vector class and some extensions to it, why shouldn't I inherit from it. – Razzupaltuff Nov 04 '21 at 18:00
  • @Yksisarvinen: Fun fact: I can derive from my own template classes and call their members without having to prefix them with "this->". So what gives? – Razzupaltuff Nov 04 '21 at 18:01
  • @Eljay: Thanks for the pointer. – Razzupaltuff Nov 04 '21 at 18:01
  • @Razzupaltuff You would need to show an example of that. gcc might allow some non-standard uses with `-fpermissive`, but you should avoid that flag at all costs. Regarding "why you shouldn't inherit from vector" - it's not prepared to be inherited from. It doesn't have a `virtual` destructor (nor any other `virtual` method), so you cannot use your derived class via `std::vector*`. If you are not allow to use polymorphism, the greatest strength of inheritance is gone and composition is typically a better choice then. – Yksisarvinen Nov 04 '21 at 19:12
  • In addition to what Yksisarvinen said, in addition to the lack of virtual methods, it also lacks protected member variable. The API is entirely public. There's nothing that you can do using inheritance that you couldn't just as well do using free standing functions passed in a `std::vector`, and the [UCFS](https://en.wikipedia.org/wiki/Uniform_Function_Call_Syntax) convenience is not a strong argument for inheritance. (Alas that `std::vector` wasn't marked `final`.) – Eljay Nov 04 '21 at 20:00
  • It's funny how std offers that kind of a class. So in the end writing my own dynamic array template class apparently was the proper way to go. And I thought I should switch to equivalent std classes. – Razzupaltuff Nov 19 '21 at 09:33

0 Answers0