Reputation:
I created a copy constructor for my class. Does any one know why l1.ptr
and l2.ptr
give me the same address after compilation? I've done it many times and don't know where the error is.
#include<iostream>
#include<string>
using namespace std;
class numb
{
public:
int* ptr;
numb(int = 3);
numb(const numb&);
virtual ~numb();
};
numb::numb(int x)
{
this->ptr = new int(x);
}
numb::numb(const numb& l1)
{
this->ptr = new int(*(l1.ptr));
}
numb::~numb()
{
}
int main()
{
numb l1(5), l2;
l1 = l2;
cout << l1.ptr << endl;
cout << l2.ptr << endl;
system("Pause");
return 0;
}
Upvotes: 0
Views: 491
Reputation: 60228
In this snippet:
numb l1(5), l2;
l2 = l1;
the second line is not calling the copy constructor. Instead, it is calling the copy-assignment operator. Since you have not defined that, you get a shallow copy.
You can either use the copy constructor, like this:
numb l1(5);
numb l2(l1);
or define the operator=
for your class:
numb& operator=(const numb&); // do a deep copy
Upvotes: 4
Reputation: 1873
By not providing an assignment operator, you get the one that the compiler generates for you. The compiler is indeed "copying the pointer" (usually referred to as 'shallow copy').
If you need to copy the pointee (usually referred to as 'deep copy'), then you have to implement your own assignment operator.
Upvotes: 0