I have this Instance of class A, which i first assign, then assign again, but the compiler calls the destructor AFTER they class has been constructed the second time, why?
class A{
public:
int *Int;
A(int b) { Int = new int(b); cout << "CONSTRUCTOR " <<endl; };
~A() { delete[] Int; cout << "DESTRUCTOR" << endl; }
};
int main(){
A Inst(3);
Inst = A(4);
cout << *Inst.Int << endl;
}
output:
CONSTRUCTOR
CONSTRUCTOR
DESTRUCTOR
0
the int should be 3, but since the class was destroyed, it is 0.
To me, a more logic behaviour would be that the compiler destructs the object BEFORE creating a new.
Is the only solution creating a member-function that changes the variable?
like
void ChangeInt(int b) { delete[] b; Int= new int(b); }
It seems a bit unecessary, since i already have a constructor that does exactly the same thing, but the destructor messes it all up.
Why?