I'm new to C++ (which is probably obvious based on below code ...) and don't manage to solve the following problem: when running below program, (*c).print();
prints values that are obviously wrong but I don't understand why. Since I haven't fully understood memory-management, I assume the problem is related to that and I hope the solution will give me a better understanding (e.g., my understanding is, that when creating an array using new, the elements of the array don't have to be created using new[?]. Specifically, Complex* aa = new Complex[3];
should be sufficient). Thanks in advance!
Console-output with the wrong data highlighted
#include <cstdlib>
#include <iostream>
using namespace std;
class Complex {
public:
double real;
double imag;
public:
Complex() {
real = 0.0;
imag = 0.0;
}
public:
Complex(double real, double imag) {
Complex::real = real;
Complex::imag = imag;
}
public:
Complex operator + (const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
public:
void print() {
if (imag >= 0) {
cout << real << " + " << imag << " i\t\t";
} else {
cout << real << " " << imag << " i\t\t";
}
}
};
class triMatrix {
public:
Complex** mat;
int dim;
public:
triMatrix(int dim, Complex* array) {
triMatrix::dim = dim;
mat = new Complex*[dim];
int k = 0;
for (int i = 0; i < dim; ++i) {
mat[i] = new Complex[dim];
for (int j = 0; j <= i; ++j) {
mat[i][j] = array[k];
++k;
}
}
}
public:
~triMatrix() {
for (int i = 0; i < dim; ++i) {
delete[] mat[i];
}
delete[] mat;
}
public:
triMatrix operator + (const triMatrix& other) {
Complex *c = new Complex[(dim + 1) * dim / 2];
triMatrix *sum = new triMatrix(dim, c);
for (int i = 0; i < dim; ++i) {
for (int j = 0; j < dim; ++j) {
sum->mat[i][j] = mat[i][j] + other.mat[i][j];
}
}
(*sum).print();
return *sum;
}
public:
void print() {
for (int i = 0; i < dim; ++i) {
for (int j = 0; j < dim; ++j) {
mat[i][j].print();
}
cout << endl;
}
}
};
int main () {
Complex* aa = new Complex[3];
aa[0] = Complex(1.2, 0.2);
aa[1] = Complex(3.2, -0.2);
aa[2] = Complex(-12.4, 0);
triMatrix *a = new triMatrix(2, aa);
(*a).print();
Complex* bb = new Complex[3];
bb[0] = Complex(-6.3, 0);
bb[1] = Complex(2.3, 0);
bb[2] = Complex(4.3, -1.2);
triMatrix *b = new triMatrix(2, bb);
(*b).print();
cout << sizeof(triMatrix) << endl;
triMatrix *c;
c = (triMatrix*) malloc(sizeof(triMatrix));
*c = *b + *a;
(*c).print();
(*a).print();
(*b).print();
}