I am doing some OOP problems and I was provided this code
int main() {
IntegerArray a(2);//This call the constructor
a.data[0] = 4; a.data[1] = 2;
if (true) {
IntegerArray b = a;
}
cout << a.data[0] << endl; // The result is 4
}
I add the indentation to the code and created the class which contains two constructors and a destructor
class IntegerArray
{
public:
int *data;
IntegerArray()
{
data = new int[1];
}
IntegerArray(int len)
{
data = new int[len];
}
~IntegerArray()
{
delete data;
}
};
int main()
{
IntegerArray a(2);//This call the constructor
a.data[0] = 4;
a.data[1] = 2;
if (true)
IntegerArray b = a;
printf("%d\n", a.data[0]);
}
The question is why does this code cause a core dump in IntegerArray b = a
isn't it copying the object a
into a new object b
, I guess this is my understanding of Exercise 3
This is the program output
0
free(): double free detected in tcache 2
Aborted (core dumped)