Copy and Move Constructors

In this lesson, you will learn about two types of constructors: copy and move.

Copy constructor

A copy constructor is a special member function with the following signature:

ClassName(const ClassName&);

It’s used when you create an object using a variable of the same type. For example:

Experiment exp { 42, 100 };
Experiment other { exp }; // copy constructor called!

Implementing a copy constructor might be necessary when your class has data members that cannot be shallow copied, like pointers, resource ids (like file handles), and many others.

Move constructor

Move constructors take R-value references of the same type:

ClassName(ClassName&&);

They are used to “steal” guts of other objects of the same type when these objects are temporary entities or their life is about to end.

Experiment exp { 42, 100 }, anotherExp;
Experiment finalExp { exp + anotherExp }; // move constructor called for the temporary!

If we assume that we can add objects of the Experiment class, then the expression exp + anotherExp creates a temporary entity passed into the move constructor. Move constructors can improve performance for large objects, especially container types and objects that manage resources.

Get hands-on with 1200+ tech skills courses.