1

Possible Duplicate:
Deep copy vs Shallow Copy
What is the difference between overloading operator= and overloading the copy constructor?

I see two ways of copying a class:

  1. Copy Constructor

  2. operator=

My question is, which one should make a new copy of dynamically allocated memory (2 classes with the same data and 2 instances of dynamic memory) and which should simply move the class to a new memory location (one class with the same dynamically allocated memory but the class is in a different place)?

Community
  • 1
  • 1
Lauer
  • 517
  • 1
  • 6
  • 11

2 Answers2

1

A copy constructor creates a new object and initializes its state based on an existing object:

A x(y); // x is now in the same state as y

An assignment operator takes an existing object and changes its state to match another existing object:

A x; // x is in the default state
x = y; // x is now in the same state as y

Whatever decisions you make about the state should apply equally to both.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
0

You must implement both because you can declare variable through copy constructor. You can assign to variable. For example:

Class a; //some heap allocations inside
Class b(a); //must be valid
Class c = a; //must be valid too

And dont forget about destructor. Simple way is achieve copy and assign operator is to use copy when assign then swap(copy&swap). Copy & swap and Rule of three

Community
  • 1
  • 1
Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44