0

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.

6
  • 5
    "It's wrong if I would implied copying, because it works as assignment of the address": no, that's not true for C++, maybe you are confusing it with C# or Java? Commented Jan 23, 2019 at 14:24
  • 2
    "[I]t works as assignment of the address" is wrong. With my_class a = b; the actual object is copied. If you have my_class& a = b; then that's another matter. Commented Jan 23, 2019 at 14:25
  • In your first case the copy ctor is called because otherwise the ctor and then the assignment operator would need to be called which is not as efficient as a copy constructor. Commented Jan 23, 2019 at 14:28
  • 1
    When you see type name = value you are never doing assignment. You are initializing name and will always be calling a constructor. Commented Jan 23, 2019 at 14:52
  • You can use the rule of five example and add your own debug output to each ctor, the dtor and the assignment operators and then make some test code using your class in different ways until you've managed to use all the functions in the class. It'll be worth it. Commented Jan 23, 2019 at 14:54

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

if (&a != this) Also, you forgot to delete x in operator= and the destructor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.