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

4
  • 2
    Why not have just a class with the matrix as an attribute? Commented Jul 11, 2021 at 20:26
  • The std:: collections are not designed to be inherited from. Commented Jul 11, 2021 at 20:29
  • Does this answer your question? Thou shalt not inherit from std::vector Commented Jul 11, 2021 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. Commented Jul 11, 2021 at 20:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.