0

What is the correct method of inheriting a standard library class to implement a new container type?

I assume that inheriting from std::vector is not the exact correct method, although I do not know whether it would actually work or not.

I assume std::vector inherits from another class and that I should inherit that class in order to implement a new type of container, is this correct, and if so what should be inherited?

Is there anything else I need to know, for example, what modifications I may need to make to the std::iterator group of objects?

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • 1
    What container type are you trying to implement? It is very likely you don't need to do so, and would be better off using composition instead of inheritance. – ahruss Aug 04 '14 at 22:39
  • 2
    This question has been asked many times. Here is one: http://stackoverflow.com/questions/4353203/thou-shalt-not-inherit-from-stdvector – glampert Aug 04 '14 at 22:47
  • There's also a lot of good discussion [here](http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt?lq=1) (it's about C#, but the topics are pretty widely applicable) – ahruss Aug 05 '14 at 01:59

1 Answers1

0

Class which inherits from vector

Matrix.h

#include <vector>
#include <iostream>

template<typename T>
class Matrix: public std::vector<T>
{
public:
   using std::vector<T>::vector;

private:
};

Matrix.cpp

int main()
{
   Matrix<int> dani;
   dani.push_back(2);
   dani.push_back(3);

   for(const auto& it: dani)
      std::cout << it << " ";
}

Class which contains a vector

You can overload operators, if you like this method you can see here the complete example class with

  • templates
  • matrix opperations
  • operators overloading

in github: here

#include <vector>
#include <iostream>
class Vector
{
public:
    Vector();
    Vector(int);
    Vector(int, int);

    ~Vector();

    std::vector<std::vector<T>> v;

    bool Check_Size() ;
    template<typename T1> bool Check_Size(std::vector<T1>&) ;
    template<typename T1> bool Check_Size_Fast(std::vector<T1>&);

    void Print();

    void Transponse();

    void Inverse();
    void Inverse2();
    void Inverse3();


    template<class T,class Q>
    friend std::vector<std::vector<T>> operator* (const Q , Vector<T> );
    ...

};
dani2442
  • 41
  • 7