#include<iostream>
using namespace std;
class test
{
int *p;
public:
test(){p=new int(0);}
test(const test &src)
{
p=new int(*src.p);
}
~test(){delete p;}
void show(){cout<<*p<<" at "<<p<<endl;}
void setx(int a)
{
*p=a;
}
};
int main()
{
test a,b;
a.setx(10);
a.show();
b=a;
b.show();
test c=a;
c.show();
}
Here inside main(), test c=a
calls the copy constructor and allocates memory for the integer. No problem with that, both c.p
and a.p
point to different memory locations. But the line b=a
causes b.p
and a.p
to point to the same memory location. I have created my own copy constructor, b.p
and a.p
should have pointed to different memory locations. What's going on here?
Edit: To be precise, my question is what's the difference between implicitly-defined copy constructor and implicitly-defined copy assignment operator?