Performance[perf]

C Copy Constructor Explained: How Objects Get Copied

Abstract

A C++ copy constructor creates a new object from an existing object of the same class, usually through a `const T&` parameter. The compiler-generated version copies members individually, which is safe for many value types but only copies a raw pointer’s address, so resource-owning classes need a deep copy or should disable copying. In practice, use resource-managing members such as `std::vector` when possible, and distinguish copying a new object from assigning to an existing one.

Hands duplicate puzzle box parts using vermilion lines from an original to a new empty box on a workbench.
Figure 1 — Hands duplicate puzzle box parts using vermilion lines from an original to a new empty box on a workbench.

Think of photocopying a signed contract. The copy looks just like the original and can be filed or marked up, yet it’s a separate sheet of paper with its own life.

A C++ copy constructor does the same job for objects: it builds a new object from an existing one.

The one-line answer: a copy constructor takes a reference to an existing object of the same class and builds a new one from it.

Here we’ll cover its signature, the default memberwise copy, deep copies, and how it differs from assignment, then see how C++11 move semantics, deleted copies, and C++17 copy elision change the picture.

How the C++ Copy Constructor Works

When C++ builds a new object from an existing one, the copy constructor does the work.

Basic rules every constructor follows

A constructor is a special member function with the same name as its class and no return value, not even void. If you write no constructor, the compiler provides a default one. Every constructor belongs to a class, so the next step is learning how to define a class.

Declare any constructor yourself, though, and that compiler-provided default is lost.

The four types of constructors are:

  1. Default: takes no arguments.
  2. Parameterized: takes arguments to set up the object’s state.
  3. Copy: builds an object from another object of the same type.
  4. Move (C++11): takes over another object’s resources instead of copying them.

Making a copy of an object

The copy constructor creates a copy of an existing object, and its parameter is a reference to its own class type. Any extra parameters need default values.

The compiler calls it when you pass or return an object by value. C++17 guarantees copy elision in specified prvalue (unnamed temporary) initialization cases, so some copies vanish.

According to Code-driven Language Development, a paper on analyzing C/C++ open-source projects, that elision “is mandated by the language” since C++17.

Count these calls with an instrumented type whose copy constructor increments a counter. Consider a game engine programmer who passes a Texture by value and can’t see why frames stutter. The count points straight at the parameter to change.

A programmer sits at a desk as faceless hands carry tablets through a doorway, spawning vermilion duplicates that pile on the floor.
Figure 2 — A programmer sits at a desk as faceless hands carry tablets through a doorway, spawning vermilion duplicates that pile on the floor.

What is the copy constructor syntax?

Every constructor shares one general form: the class name, a parameter list, an optional member initializer list after a colon, and a body. The copy constructor’s signature is T(const T&), so a Widget class declares Widget(const Widget& other).

Direct syntax, Widget w2(w1);, passes the source in parentheses. Assignment-style initialization, Widget w2 = w1;, still calls the copy constructor, so it’s initialization, not assignment.

The const lets you copy from const objects, non-const objects, and temporaries alike.

Why the parameter must be a reference

Why not take the parameter by value? That would require a copy, which calls the copy constructor, which needs another copy, and so on. That’s infinite recursion, so C++ doesn’t allow it.

A reference breaks the cycle, because binding to the existing object makes no copy at all. The fix is a reference instead of a value.

The Compiler’s Automatic Copy Constructor

If you don’t write a copy constructor, the compiler writes one for you. That’s convenient until your class holds a raw pointer, so let’s see where it breaks.

Copying each member one at a time

When your class declares no copy constructor, the compiler supplies one. It copies each data member one at a time. For a simple class, that’s usually all you need.

Consider a graphics developer who writes a small Point struct with two double fields for a drawing tool. The generated copy constructor copies both correctly. Nothing to fix here.

Pointer copies that cause trouble

The default copy is only as good as the members it copies. If a member is a raw pointer, the compiler copies the pointer, not the pointee. Both objects now hold the same address, a shallow copy, and the trouble follows in three steps:

  1. Both objects share one block of memory.
  2. One object is destroyed and frees that block.
  3. The other is left with a dangling pointer, an address to memory it no longer owns.

Think of a firmware developer whose SampleBuffer owns a heap array of sensor readings. A copy gets made to hand data to a logging routine, and nothing looks wrong.

Once that copy is destroyed, the original’s next read is undefined behavior, and the crash may surface far from the cause.

The fix is to override the default. Write your own copy constructor that allocates new storage and copies the contents into it, a deep copy. Once you declare one, the compiler stops generating its own, so that job is yours.

A split diagram contrasts a broken, shared connection with two independent, intact systems using steel blue and vermilion ink.
Figure 3 — A split diagram contrasts a broken, shared connection with two independent, intact systems using steel blue and vermilion ink.

Write Your Own Copy Constructor

For a class that owns memory, the copy constructor’s job is to give the copy memory of its own.

Allocating new memory for each copy

A game engine programmer copies an IntArray of particle IDs into a scratch buffer.

If the copy shares the original’s pointer, destroying the scratch copy frees data the original still uses, and the next read is undefined behavior (UB). The fix is a deep copy:

  • Allocate new memory sized to match the source.
  • Copy contents, not addresses, element by element.
[Example 1:
IntArray(const IntArray& other)
    : size_{other.size_}, data_{new int[other.size_]} {
    for (std::size_t i = 0; i < size_; ++i) data_[i] = other.data_[i];
}
~IntArray() { delete[] data_; }

— end example]

Each new[] needs a matching delete[], so pair the copy constructor with a destructor that frees the buffer. Then test with a copied object: change the copy and confirm the original is untouched. If the original changed too, you’ve shared memory somewhere.

Prefer std::vector over a raw array: its copy constructor deep copies for you, so you have nothing to allocate or free by hand.

Java copy constructors compared with C++

Here’s a Java Guy class with a copy constructor:

[Example 2:
class Guy {
    String name;
    Guy(Guy other) { this.name = other.name; }
}

— end example]

Here’s how we’d write the C++ version with a member initializer list:

[Example 3:
struct Guy {
    std::string name;
    Guy(const Guy& other) : name{other.name} {}
};

— end example]

The difference is when the value arrives: the C++ version initializes name before the body runs, while Java assigns it afterward.

In Java, a copy constructor is just an ordinary constructor, with no special treatment from the language. Same shape, different rules.

Stopping Objects from Being Copied

If your class owns a file handle or a GPU resource, it should never be copied at all. Here’s how to forbid it and how the compiler enforces that rule.

Blocking copies with a private constructor

Before C++11, the usual trick was to declare the copy constructor as private and leave it undefined. It takes three steps:

  1. Declare it private. Put the declaration under private: and skip the body.
  2. Block pass and return by value. Passing a named object by value, or returning a named local by value, needs an accessible copy constructor, so that code stops compiling.
  3. Let the compiler flag the error. The error appears at compile time, not as a double release discovered at run time.

Members and friends of the class still have access, so they’re the only code that can even attempt a copy. Think of a game engine programmer who wraps a GPU texture handle in a Texture class.

Copying it would leave two objects releasing one handle, so the team declares the copy constructor private. The next pull request that passes a Texture by value fails to build, and the reviewer catches it before merge.

Since C++11, = delete replaces the private declaration: Texture(const Texture&) = delete;. A deleted function is off-limits to every caller, including members and friends, and the error says the function is deleted.

Read the signature, and the rule is right there.

A craftsman's bench with a blueprint, brass keys, and a duplicating press blocked by a steel bar.
Figure 4 — A craftsman's bench with a blueprint, brass keys, and a duplicating press blocked by a steel bar.

The copy constructor rarely works alone, and you’ll see these related ideas in most code reviews.

Other patterns worth knowing

A cast constructor (usually called a converting constructor) takes one argument of another type, letting the compiler convert that type into your class. It’s handy, but it can surprise you, so mark it explicit unless you want that conversion.

The Rule of the Big Three says that if you write a destructor, copy constructor, or copy assignment operator, you probably need all three. The copy constructor (T(const T&)) builds a new object.

The copy assignment operator (T& operator=(const T&)) overwrites an existing one, so it must clean up old contents and guard against self-assignment. The Rule of Five adds the move constructor and move assignment operator (C++11).

The Rule of Zero is the goal: if your members manage their own resources, like std::string or std::unique_ptr, write none of the five. Less code means fewer bugs.

Main points to remember

  • Reference to existing object. The copy constructor takes a const T& to an existing object and copies its state.
  • Auto-invoked on by-value passing. Passing an existing object by value calls the copy constructor, so each call copies the whole object.
  • Private copy constructor restricts copying. Declare it private, or use = delete (C++11 and later), to stop callers from copying the class.
  • Be cautious with dynamic members. The default copy is a shallow copy: it duplicates a raw pointer, not the memory behind it. Write a deep copy that allocates its own memory, or use a smart pointer.

Consider a game engine programmer whose Texture class owns a raw pixel buffer. A teammate passes it by value to a helper, and the default copy duplicates only the pointer. Both objects then free the same buffer, and the game often crashes on shutdown.

A deep copy, or a std::vector member that manages its own memory, removes that crash.

The copy constructor decides what copying means for your class. Let the compiler write it when every member is safe to copy, write a deep copy when your class owns a resource, and delete it when a copy makes no sense.

Then count the copies yourself, because a counter doesn’t guess. Add a print statement to each constructor and you’ll see what the code really does. Trust the counter over your memory.

References

  1. Code-driven Language Development: Framework for Analysis of C/C++ Open-Source Projects — doi.org (2021)

Questions

What is a copy constructor and what does it do?

A copy constructor creates a new object by copying an existing object of the same class. It typically takes a `const` reference to the source, as in `Widget(const Widget& other)`.

What is the syntax of constructor in C++?

A constructor has the class name, a parameter list, an optional member initializer list, and a body; it has no return type. For example: `Widget(int value) : value_{value} {}`. A copy constructor uses a signature such as `Widget(const Widget& other)`.

What are the four types of constructors?

The four common types are default constructors, parameterized constructors, copy constructors, and move constructors. Move constructors were introduced in C++11 and transfer resources rather than copying them.

Read next

  1. When to mark a move constructor noexcept in C++Performance · Miriam Castellanos · written for C++20
  2. C++ constructor: default, parameterized, copy and moveLanguage · Miriam Castellanos · written for C++11
  3. memcpy in C++: how std::memcpy works and when to use itPerformance · Miriam Castellanos · written for C++17