Here is the code:
class A {
private:
int *anArr;
int id;
public:
A() {
id = 0;
anArr = new int[10];
}
A(int i) {
id = i;
anArr = new int[10];
}
~A() {
delete[] anArr;
std::cout << "Class A id : " << id << " destructor" << std::endl;
}
};
class B {
private:
A *anArr;
public:
B() {
anArr = new A[10];
}
~B() {
std::cout << "Class B destructor" << std::endl;
delete[] anArr;
}
void changeAnElement() {
anArr[2] = A(1);
anArr[2] = A(2);
}
};
int main()
{
B b;
b.changeAnElement();
return 0;
}
Output:
Class A id : 1 destructor
Class A id : 2 destructor
Class B destructor
Class A id : 0 destructor
Class A id : 0 destructor
Class A id : 0 destructor
Class A id : 0 destructor
Class A id : 0 destructor
Class A id : 0 destructor
Class A id : 0 destructor
// Gives heap error here
So if I'm not wrong, when I change an element of object array it does not call destructor.
My first question is what happens to old object at the changed index? Does the array in it leak? I thought that I need to call destructor myself to prevent memory leak but it gives heap error.
Second question is I'm getting heap error (Expression: _CrtlsValidHeapPointer(block)
) when destructor of the changed object called. I have no idea why, it works fine for the ones created in constructor.
Thanks!