class destructor

Hi all,

I have a simple class and have problem with the destructor. In the code posted hereafter, the following works well:

A+B+C;

but I have problem with:

C = A+B;

in which the destructor is called with a wrong pointer.

I would like to understand why it works in the first case and not in the second.

Thanks in advance,

Nguyen

Here are the code:

1)main:
-----------
#include "classmatrix1D.h"
#include <iostream>
using std::cout;
int main()
{
int m = 3;
matrix1D A(m), B(m), C(m);
for (int i = 1; i < m+1; ++i) {
A(i) = 0.01 * i;
B(i) = i;
C(i) = 100*i;
}
A+B+C;
C = A+B;
}

2) classmatrix1D.h:
------------------
class matrix1D {
public:
matrix1D(int rows = 0);
~matrix1D();
double& operator()(int i);
matrix1D operator=(const matrix1D &A);
matrix1D operator+(const matrix1D &A);
private:
double *p;
int m;
};

3) classmatrix1D.cc:
-------------------
#include "classmatrix1D.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using std::cout;
//************************************************
matrix1D::matrix1D(int rows)
{
int i;
m = rows;
p = new (std::nothrow) double [m];

for (i=0; i<m; i++){
p[i] = 0.0;
}
}
//************************************************
matrix1D::~matrix1D () {
delete[] p;
}
//************************************************
matrix1D matrix1D::operator=(const matrix1D &A)
{
for (int i = 1; i < m+1; ++i) {
p[i-1] = A.p[i-1];
}
}
//************************************************
matrix1D matrix1D::operator+(const matrix1D &A)
{
matrix1D temp(m);
for (int i = 1; i < m+1; i++) {
temp.p[i - 1] = p[i - 1] + A.p[i - 1];
}
return temp;
}
//************************************************
double &matrix1D::operator()(int i)
{
return p[i - 1];
}





Last edited on
[code]
1
2
3
4
5
6
7
matrix1D matrix1D::operator=(const matrix1D &A)
{
  for (int i = 1; i < m+1; ++i) {
    p[i-1] = A.p[i-1];
  }
  //return ?
}
[/code]
You also need to write a copy constructor.
Thanks to ne555 and jsmith. I add the return and it works:

1
2
3
4
5
6
7
matrix1D & matrix1D::operator=(const matrix1D &A)
{
  for (int i = 1; i < m+1; ++i) {
    p[i-1] = A.p[i-1];
  }
  return *this;
}


To jsmith: what is the reason that we can not or should not use the default copy constructor created by the compiler? Because of the pointer with "new"? As in the case of the copy assignment operator?

Thanks,

Nguyen

Last edited on
Yes, exactly.

As a general rule, (in C++ it is called the "rule of three"), if you need to write a custom destructor, custom assignment
operator, or custom copy constructor, then you need to write all three.
Thank you again, jsmith.

Nguyen
Topic archived. No new replies allowed.