I've made a Matrix class that contains arrays, however I'd like to inherit the array class if possible. I've done some searching online and can't find any solid information on this. Does anyone know if I can even inherit this class? If so, do you have a good site with some reference info I can bookmark?

If anyone may have any other ideas on a container class to inherit for a Matrix class, feel free to share :)

Thanks,

Miss VavaZoom

Which array class? Standard C++ does not define such a class, though the TR1 extensions (which are blessed in C++0x) do provide a fixed array class. Without knowing the library you're using, it's hard to make a suggestion.

Though honestly, an array class is easy to write. And the only tricky part of a matrix class is getting multi-dimensional subscripting using operator overloads to work as intended.

No you cannot inherit an array because if i'm not wrong it is considered to be POD(Plain Old Data) in C++ and doesn't have ctors etc.

I don't see why a Matrix class should inherit any container. Containing an array or a vector seems like a logical solution to me.

Edit: <Too Late.. >

My Matrix class contains a 2D array right now. Everything works fine, but I'm trying to make it more efficient and a little neater. When I want to create a new matrix, I have to do

someMatrix.matrix[i,j];

And was more or less looking to be able to do

someMatrix[i,j];

Overloading the [ ] is a possibility, however I wanted to just check on the inheritance. Thanks though!

Well, you're not going to get exactly what you want, but you can get reasonably close. For example:

template <typename T, int M, int N>
class Matrix {
    T _base[M][N];
};

int main()
{
    Matrix<int, 2, 4> mat; // 2x4 matrix
}

Or for dynamic sizing:

template <typename T>
class Matrix {
    T **_base;
    int m, n;
public:
    Matrix(int m, int n)
        : m(m), n(n)
    {
        _base = new T*[m];

        for (int i = 0; i < m; i++)
            _base[i] = new T[n]();
    }

    ~Matrix()
    {
        for (int i = 0; i < m; i++)
            delete[] _base[i];

        delete[] _base;
    }
};

int main()
{
    Matrix<int> mat(2, 4); // 2x4 matrix
}

Thanks, this helps me out a lot. I appreciate it.
One question, I have never seen this:

Matrix(int m, int n)
: m(m), n(n)

Which var is the one being passed into Matrix? The ones in the ()?

It's <data member>(<value>). The names can be the same because it's easy to parse without ambiguity in an initialization list. If you did it in the body of the constructor, matters would be different:

Matrix(int m, int n)
{
    this->m = m; // "this->" required
    this->n = n; // "this->" required
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.