C++20 sections · 1024 units
Open in Course

Default vs Custom Copy Constructor

Shallow vs deep copy

The default copy constructor does a shallow copy: it copies member values directly. If a member is a pointer, it copies the address, not the data it points to. Now both objects share the same memory.

This breaks when destructors run. Both objects try to delete the same memory, causing a double-free crash. Or one object modifies shared data, unexpectedly changing the other. Write a custom copy constructor to do a deep copy: allocate new memory and copy the data.

Now each object owns independent resources.