Guilherme Salome
Guilherme Salome

Reputation: 2039

Simple Matrix class, error: calling private constructor

I am learning C++ and trying to construct a simple Matrix class. The basic case I have defines the Matrix class as:

class Matrix {
    int r; // number of rows
    int c; // number of columns
    double* d; // array of doubles to hold matrix values
    Matrix(int nrows, int ncols, double ini = 0.0);
    ~Matrix();
}

And the constructor/destructor are:

Matrix::Matrix(int nrows, int ncols, double ini) {
    r = nrows;
    c = ncols;
    d = new double[nrows*ncols];
    for (int i = 0; i < nrows*ncols; i++) d[i] = ini;
}
Matrix::~Matrix() {
    delete[] d;
}

Problem: when I instantiate the class Matrix by calling Matrix my_matrix(2,3), I get the following errors: error: calling a private constructor of class 'Matrix',error: variable of type 'Matrix' has private destructor.

Question: Why is this happening? How can I understand what is failing? Could someone point me towards the solution/reading materials to help me understand this problem. Thanks for helping!

Upvotes: 0

Views: 613

Answers (1)

Omni
Omni

Reputation: 1022

By default, the access to properties/methods of a class is private. Add a public: statement in your class:

class Matrix {
    int r; // number of rows
    int c; // number of columns
    double* d; // array of doubles to hold matrix values
public:    
    Matrix(int nrows, int ncols, double ini = 0.0);
    ~Matrix();
}

Upvotes: 2

Related Questions