Reputation: 249
C++ requires create constructor of copies for assignment one instance to another instance. For example:
my_class a = b;
It's wrong if I would implied copying, because it works as assignment of the address. Therefore, if I change a
, b
will be changed too. So, I should create constructor of copy:
my_class(const my_class &obj);
It seems as obvious thing and rest is going without saying, but I have gotten a doubt, when I found out about overload operators:
my_class operator=(my_class obj);
Turns out that I could use it as assignment and I don't have to use constructor of copies. Is that right? However, why assignment that is placed in the definition of operator=
works as copying.
Upvotes: 0
Views: 61
Reputation: 51
You can use or the copy assignment, as well as the constructor of copies.
class A {
A(const A& a);
A& operator=(const A& a);
};
A a1;
A a2(a1); // calling constructor of copies A(const A& a);
A a2 = a1; // also calling constructor of copies A(const A& a);
A a3;
a3 = a1; // calling copy assignment operator=(const A& a);
Here is example implementation:
class A
{
public:
int* x;
A(int data)
{
this->x = new int(data);
}
A(const A& a)
{
this->operator=(a);
}
A& operator=(const A& a)
{
this->x = new int(*a.x);
return *this;
}
};
Also you can provide special checks to avoid self-assignment, e.g. if (a != this)
Upvotes: 1