I am trying to understand the concept of copy constructor. I used this example:
#include <iostream>
using namespace std;
class Line
{
public:
int GetLength();
Line(int len);
Line(const Line &obj);
~Line();
private:
int *ptr;
};
Line::Line(int len)
{
ptr = new int;
*ptr = len;
};
Line::Line(const Line &obj)
{
cout << "Copying... " << endl;
ptr = new int;
*ptr = *obj.ptr;
};
Line::~Line()
{
delete ptr;
};
int Line::GetLength()
{
return *ptr;
}
int main()
{
Line line1 = Line(4);
cout << line1.GetLength() << endl;
Line line2 = line1;
line1.~Line();
cout << line2.GetLength() << endl;
return 0;
}
The question is, why do I get runtime error here? If I defined a copy constructor which allocates memory for the new ptr, and assigned the line1 to line2, doesn't that mean that those two are separate objects? By destructing line1, I obviously mess up line2 as well, or am I using the destructor call wrong?