0

I have to modify a code so that I can add a member to 2D vectors. The code started with a typedef vector<vector<int>> Matrix which I replaced with a Matrix class. I tried to inherit from vector<vector<int>> using :

class Matrix: public vector<vector<int>> {
public:
    int myMember;
};

This way I practically don't have to modify the source code much. However, if I try to run :

Matrix mymatrix (4);

It raises an error :

modele.cpp:19:20: error: no matching function for call to 'Matrix::Matrix(int)'
  Matrix mymatrix (4);
                    ^
In file included from modele.cpp:8:0:
modele.h:6:7: note: candidate: Matrix::Matrix()
 class Matrix: public vector<vector<int>> {
       ^
modele.h:6:7: note:   candidate expects 0 arguments, 1 provided
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 7
    1. Constructors aren’t inherited by default. 2. Inheriting from standard library containers is *generally* not a great idea. It works under certain circumstances but it’s usually better to create an explicit public interface and use composition instead of inheritance. 3. A matrix is poorly represented by a nested vector. A better representation is via a flat array/vector, and with a suitable `operator()` overload which accepts `i`, `j` indices as arguments. Besides a superior interface, this is also vastly more efficient due to memory contiguity. – Konrad Rudolph Nov 24 '21 at 15:39
  • [Very simple example of above](https://stackoverflow.com/a/2076668/4581301) – user4581301 Nov 24 '21 at 16:33
  • @KonradRudolph 1. Thank you. 2. Yes, I've read on multiple threads that thou shalt not inherit from standard library containers but in my specific case, I think it will work just fine. 3. Agreed, using a flat array is way more efficient. But it was mandatory to use nested vectors as it's required by the professor. – Redwane Hammas Nov 25 '21 at 10:02

1 Answers1

1

Constructors are not inherited by default, but can use them in your derived class for that you have to do something like this:

#include <vector>
#include <iostream>
class Matrix : public std::vector<std::vector<int>>{
    public:
        using vector::vector;
        int myMember;
};

int main(){
    Matrix data(1);
    std::vector row = {1,2,3,4,5};
    data.push_back(row);


    for(auto i: data){
        for(auto r : i){
            std::cout << r << std::endl;
        }
    }
}

This way compiler will know all the constructors from the base class. And will call the appropriate constructor for your derived class.

foragerDev
  • 1,307
  • 1
  • 9
  • 22