I wrote class Complex using pointers and new keyword for allocating memory in heap. I overloaded + operator and = operator also. Everyting works fine until i use destructor to free allocated memory. Destructor is causing runtime error in Visual Studio. . i think it is something related to deallocating memory on heap that is causing this problem. Run the code on Visual Studio. I also noticed that problem of destructor is associated with overloaded + operator. Please help me to overcome this issue. In VS
I am attaching image of error , produced by Visual Studio
#include<iostream>
using namespace std;
class Complex {
private:
int *real;
int *complex;
public:
// some declarations
Complex();
Complex(int, int);
Complex operator+ (const Complex& rhs);
Complex& operator= (const Complex& rhs);
void disp() {
cout << "(" << *real << "," << *complex << ")" << endl;
}
// destructor
~Complex() {
delete real;
real = nullptr;
delete complex;
complex = nullptr;
}
};
// overloading + operator
Complex Complex::operator+ (const Complex &rhs) {
int a, b;
a = *(this->real) + *(rhs.real);
b = *(this->complex) + *(rhs.complex);
Complex temp(a,b);
return temp;
}
// overloading = operator
Complex& Complex::operator= (const Complex& rhs) {
*(this->real) = *(rhs.real);
*(this->complex) = *(rhs.complex);
return *this;
}
// no-args constructor
Complex::Complex() {
real = new int;
*real = 0;
complex = new int;
*complex = 0;
}
// parameterized constructor
Complex::Complex(int x,int y) : Complex() {
*real = x;
*complex = y;
}
int main() {
Complex n1(5,-9);
Complex n2(2, -1);
Complex n3;
n3= n1 + n2;
n3.disp();
return 0;
}