5

What happens (exactly) if you leave out the copy-constructor in a C++ class?

Is the class just memcpy'd or copied member wise?

horstforst
  • 973
  • 5
  • 4

4 Answers4

8

The class is copied member-wise.

This means the copy constructors of all members are called.

mmmmmmmm
  • 14,867
  • 2
  • 29
  • 54
1

The default copy constructor is made mebmber wise.

The same member-wise approach is also used for creating an assignment operator; the assignment operator however is not created if the class has reference members (because it's impossible to rebind a reference after construction).

6502
  • 108,604
  • 15
  • 155
  • 257
0

You get the default copy that copies the contents from one object into the other one. This has the important side effect that every member containing a pointer is now shared between the original object and the copy.

Stefano Borini
  • 132,232
  • 95
  • 283
  • 413
0

Notice that with a member-wise copy, if you have allocated any memory, your data structures will share that memory allocated - so it is important, if you want to create a deep (independent) copy of data to create a copy constructor for structures which allocate memory. If your structure is not allocating memory, it is less likely to really require a copy constructor.

However, if you implement the copy constructor, don't forget the Rule of Three: copy constructor, assignment operator, destructor. If one is implemented, all three must be implemented.

Regards,
Dennis M.

RageD
  • 6,503
  • 4
  • 28
  • 37