Why You Need Copy Constructors in C++

By Stephen R. Davis

The constructor is a special function that C++ invokes automatically when an object is created to allow the object to initialize itself. There are two particular variations of the constructor known as the copy and move constructors.

A copy constructor is the constructor that C++ uses to make copies of objects. It carries the name X::X(const X&), where X is the name of the class. That is, it’s the constructor of class X, which takes as its argument a reference to an object of class X. This sounds really useless, but just take a minute to explore why C++ needs such beasties.

Think for a moment about what happens when you call a function like the following:

void fn(Student fs)
{
    // ...same scenario; different argument...
}
int main(int argcs, char* pArgs[])
{
    Student ms;
    fn(ms);
    return 0;
}

In the call to fn(), C++ passes a copy of the object ms and not the object itself.

Now consider what it means to create a copy of an object. First, it takes a constructor to create an object, even a copy of an existing object. C++ could create a default copy constructor that copies the existing object into the new object one byte at a time.

That’s what older languages such as C do. But what if the class doesn’t want a simple copy of the object? What if something else is required? (Ignore the “why?” for a little while.) The class needs to be able to specify exactly how the copy should be created.

Thus, C++ uses a copy constructor in the preceding example to create a copy of the object ms on the stack during the call of function fn(). This particular copy constructor would be Student::Student(Student&) — say that three times quickly.