I made a program that substract two arrays from 2 objects of the same class and then put them in a new array and display them. The program work until the end when he crashes. I think it's the destructor because if i remove him the program exit normally I don't know why I think I allocated correctly memory still...
#include <iostream>
using namespace std;
class math{
private:
float *tab;
float *result;
int size;
public:
math(int n);
void subtract(math,int);
void afis(){
cout<<"Result of subtraction: ";
for(int i=0;i<size;i++)
cout<<result[i]<<",";
}
~math(){delete []tab;delete []result;} //if i remove this program exit normally
};
math::math(int n){
cout<<"Write elements: ";
tab=new float[n];
result=new float[50];
for(int i=0;i<n;i++)
cin>>*(tab+i);
}
void math::subtract(math y,int x){ //if i dont call this the program exit normally with destructor
size=x;
for(int i=0;i<x;i++)
result[i]=tab[i]-y.tab[i];
}
void main(void){
int n1,n2;
cout<<"Write elements of sir1: ";
cin>>n1;
math sir1(n1);
cout<<"Write elements of sir2: ";
cin>>n2;
math sir2(n2);
sir1.subtract(sir2, n1<n2 ? n1:n2); //also if i comment this line the program exit normally with or without destructor
sir1.afis();
cin.ignore();
cin.get();
}
PS: Hm i debug my code and it seems like a destructor is calls twice for the same object. So is this destructor right before subtract function and two destructors at the end, in total 3 destructors instead of 2. I don't understand why. PS2: I fix my problem by using math & parameter in subtract instead of math but i don't undertand why this called the destructor. Now my program works normally with delete. But can someone give me an explanation?