6

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
  • 1,073
  • 6
  • 4

4 Answers4

9

The class is copied member-wise.

This means the copy constructors of all members are called.

mmmmmmmm
  • 15,269
  • 2
  • 30
  • 55
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
  • 112,025
  • 15
  • 165
  • 265
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
  • 138,652
  • 96
  • 297
  • 431
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,693
  • 4
  • 30
  • 37