0

I would like to know if I can create a class that inherits a vector that contains vectors (2d) and can write my own methods.

using matrix = vector<vector<float>>;

class MyClass: public matrix;

...

MyClass m;

m = {{1,2,3}, {4,5,6}, {7,8,9}}

m.randomize(); // my method
m.pop_back() //class vector method

  • 2
    Why not have just a class with the matrix as an attribute? – ShadowMitia Jul 11 '21 at 20:26
  • The `std::` collections are not designed to be inherited from. – Richard Critten Jul 11 '21 at 20:29
  • Does this answer your question? [Thou shalt not inherit from std::vector](https://stackoverflow.com/questions/4353203/thou-shalt-not-inherit-from-stdvector) – Richard Critten Jul 11 '21 at 20:32
  • @RichardCritten _"The std:: collections are not designed to be inherited from"_ That's not exactly true. They don't have `virtual` destructors which means they can't be deleted polymorphically from a base pointer; but there is nothing that prohibits them being inherited from. Even the answers on the linked question indicate the same. I'm not suggesting inheriting is good advice in this case; just that stating they are "not designed to be inherited from" is factually incorrect. – Human-Compiler Jul 11 '21 at 20:38

2 Answers2

4

I would like to know if I can create a class that inherits a vector that contains vectors (2d) and can write my own methods

Yes, nothing prohibits this although it's generally recommended to use composition instead. One reason why it's not recommended is that the standard containers destructor is not virtual so deleting objects though base class pointers doesn't work.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
3

Sure, but that’s not what you want. Why should MyClass have a push_back method which can be used to make the matrix non-square? Why should its resize method set the number of rows but not the number of columns? Inheriting from a non-abstract class is almost never a good idea, compared to either composition or refactoring.

Sneftel
  • 40,271
  • 12
  • 71
  • 104