Solved

# Is this a justified explicit call of a destructor ?

Posted on 2003-12-07

Ah hello.

I would appreciate it if you could please examine the following code, with particular attention being paid to

Matrix& Matrix::operator=(const Matrix& rhs)

Have I coded this correctly, and is there any need for it to be virtual ?

Cheers.

#include <iostream>

using std::cout;

using std::endl;

using std::ostream;

class Matrix

{

public:

Matrix(int r, int c) : nr(r), nc(c), data(memory_allocate(r, c)) { intialise(); }

Matrix(const Matrix& m);

virtual ~Matrix() = 0;

double& operator() (int i, int j){ return data[i][j]; }

friend ostream& operator << (ostream& os, const Matrix& rhs);

virtual ostream& print(ostream& os) const;

virtual Matrix& operator=(const Matrix& rhs);

protected:

int nr; // Number of rows

int nc; // Number of cols

double** data;

double** memory_allocate(int r, int c);

void intialise();

};

Matrix::Matrix(const Matrix& m) : nr(m.nr), nc(m.nc), data(memory_allocate(m.nr, m.nc))

{

for (int i = 0; i < nr; ++i) {

for (int j = 0; j < nc; ++j) {

data[i][j] = m.data[i][j];

}

}

}

Matrix::~Matrix() {

for (int i = 0; i < nr; i++) {

delete[] data[i];

}

delete[] data;

}

double** Matrix::memory_allocate(int r, int c)

{

double** temp;

temp = new double*[r];

for (int i = 0; i < r; i++) {

temp[i] = new double[c];

}

return temp;

}

ostream& operator << (ostream& os, const Matrix& rhs)

{

return rhs.print(os);

}

ostream& Matrix::print(ostream& os) const

{

for (int r = 0; r < nr; r++) {

for (int c =0; c < nc; c++) {

os << data[r][c] << "\t";

}

os << "\n";

}

return os;

}

Matrix& Matrix::operator=(const Matrix& rhs)

{

if (this != &rhs) {

this->~Matrix();

memory_allocate(rhs.nr, rhs.nc);

this->intialise();

}

return *this;

}

void Matrix::intialise()

{

for (int r = 0; r < nr; r++) {

for (int c =0; c < nc; c++) {

data[r][c] = 0;

}

}

}

class Vector : public Matrix

{

public:

Vector(int nr, int nc) : Matrix(nr, nc) {}

Vector(const Vector& v) : Matrix(v) {}

virtual ~Vector() = 0 {};

virtual double& operator[] (int i) = 0;

virtual double operator[] (int i) const = 0;

virtual ostream& print(ostream& os) const;

};

ostream& Vector::print(ostream& os) const

{

return (Matrix::print(os));

}

// Assuming one row, varying number of columns, eg xxxxx is a row vector of size 5

class RVector : public Vector

{

public:

RVector(int nc) : Vector(1, nc) {}

~RVector() {}

// Called for assignment/retrieval on a NONE CONSTANT object only

virtual double& operator[](int i) { return data[0][i]; }

// Called for assignment/retreival on a CONSTANT object only

virtual double operator[](int i) const { return data[0][i]; }

};

int main()

{

RVector r(10);

RVector s(10);

cout << s << endl;

for (int i = 0; i < 10; i++) {

s[i] = 10;

}

s = r;

//r.~RVector();

cout << s << endl;

return 0;

}