mercredi 17 octobre 2018

c++, Object of class changes when creating a new object

I have created a class matrix that besides having some member functions, operators and a constructor has two variables:

int m, which is the dimension (side length) of the quadratic matrix

double a[], which contains the elements of the matrix.

As long as I only create one matrix object A all seem to work fine and all my member operators and functions work as they should.

My problem is that once I create a second object B of the class matrix the variables of object A changes as well.

The relevant code is as follows:

class Matrix{
    private:
        const int m;
        double a[];
    public:
        Matrix(int inpm);
        void fillMatrix(const double inpa[]);
};
Matrix::Matrix(int inpm): m(inpm){
    a[impm*inpm];
}
void Matrix::fillmatrix(const double inpa[]){
    for (int i ; i<m*m ; i++){
        a[i]=inpa[i];
    }
}

int min =2;
double ain[min*min] = {1,2,3,4};
double bin[min*min] = {5,6,7,8};

Matrix A(min);
Matrix B(min);

A.fillMatrix(ain);
//A looks precisely as it should here:
//m=2, a={1,2,3,4}
B.fillMatrix(bin);
//Here B looks as it should but A has changed to:
//m=0, a={7,8,3,4}

obviously the change to the first object occur when I run fillMatrix() for the second object but I cannot figure out why, especially since m is a constant integer.

I'm really stuck so grateful for all help.

PS: I use another member function "void printMatrix();" using std:cout to look at the values of m and all elements in a.

Aucun commentaire:

Enregistrer un commentaire