I have the following code that behaves weirdly. The flow I understood so far is, display(line); will call the copy constructor Line::Line(const Line &obj), and the reference of line will be passed in. However cout<<"[origin] *ptr="<<*obj.ptr<<endl; will print [origin] *ptr=32767 instead of [origin] *ptr=10.
The more weird thing is, if I uncomment // int x=3;, it will print correctly, but I really have no idea why.
You may find the executable code at: https://www.onlinegdb.com/pjbPO0X1f
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len );
Line( const Line &obj);
private:
int *ptr;
};
// constructor
Line::Line(int len)
{
ptr=&len;
cout<<"*ptr="<<(*ptr)<<endl;
}
// copy constructor
Line::Line(const Line &obj)
{
// int x=3;
cout<<"[origin] *ptr="<<*obj.ptr<<endl;
ptr = new int;
*ptr = *obj.ptr; // copy
}
int Line::getLength( void )
{
return *ptr;
}
void display(Line obj)
{
cout << "line=" << obj.getLength() <<endl;
}
int main( )
{
Line line(10);
display(line);
return 0;
}