1

There is a class A with 2 objects A1 and A2.

Now to assign the member values of A2 to A1, I could have used either simply A1 = A2, or use a copy constructor instead like :-

A (A &A2)
{
   this.m = A2.m;
   this.n = A2.n;
}

So, I want to know that which one is better and where which option is suitable or is there really any difference between them ?

King
  • 183
  • 10
  • [What's the difference between assignment operator and copy constructor?](http://stackoverflow.com/questions/11706040/whats-the-difference-between-assignment-operator-and-copy-constructor) – David G Jul 18 '14 at 17:10
  • The constructor should take a `const` reference to `A`, not a non-`const` reference. – John Dibling Jul 18 '14 at 17:10

2 Answers2

11

Firstly, you would need to do this->m, because this is a pointer.

Secondly, a copy constructor should usually take a const A&.

Thirdly, if you need to implement a copy constructor, you probably also need to implement the assignment operator. In this case, I'm not sure you actually need to implement either (just default them).

Fourthly, the copy constructor and assignment operator are used in different situations:

A A1 = A2; // Copy constructor
A1 = A2; // Assignment

You should provide both.

Fifthly, you could better write your constructor with a member initialisation list:

A(const A& A2) 
  : m(A2.m), n(A2.n)
{ }
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 1
    Six, you can explicitly default them reducing much work: `= default;`. Seven, under specific circumstances even explicitly defaulting is make-work. – Deduplicator Jul 18 '14 at 17:17
1

It depends on what you want to achieve.

If you want to make a shallow copy of your object, then a plain assignment is enough.

However, if you are in a case where your object manages pointers (calls new in constructor and delete in destructor), then you need to use the copy constructor and create a copy of each field, otherwise you could be accessing pointers of invalid state.

Snaipe
  • 1,191
  • 13
  • 25