I am a bit new to Objects in C++, and I have the following simplified problem:
I want to create an array of objects that are already initialized by the constructer of the class.
Thus:
int main() {
Test A(1);
Test B(2);
Test C(3);
Test TestArray[3]={A,B,C};
/*
Code that both uses A,B,C directly and TestArray
*/
return 0;
}
Importantly, the class Test
dynamically allocates its value. And so the destructor should delete this allocated memory.
Thus:
class Test {
int *PointerToDynMem;
public:
Test(int);
~Test();
};
Test::Test(int a){
PointerToDynMem=new int(a);
}
Test::~Test(){
delete PointerToDynMem;
}
I think what happens is when the program ends A
,B
and C
go out of scope and call the destructor. But it seems that also when TestArray
goes out of scope, it also calls the destructor, but A
,B
,C
were already deallocated soo. ERROR.
I always coded like this with normal type objects like an integer, and here it never gave me any problem. It seems that I need to change something, but don't know exactly how, since I want to both us the objects separately and have an array of them.
The thing I am confused about is why the Array should call that destructor, since it is basically a pointer to the first element and so not really an object going out of scope.