liveBook · Manning

Copy constructor

As explained in Object-Oriented Software Design in C++

A constructor that initializes a new C++ object from an existing object of the same type.

A copy constructor initializes a new C++ object from an existing object of the same type. C++ invokes it automatically when objects are copied, including during vector operations, so seemingly simple code can perform hidden construction, destruction, allocation, and deallocation. The copy constructor, copy assignment operator, and destructor form the Big Three; explicitly implementing one generally calls for implementing all three. section 6.2.2

Copying Date objects

An instrumented Date class defines Date(const Date& other), prints a message, and copies year, month, and day member by member. Appending Date values to a vector, inserting them, returning them, and printing them exposes repeated copy-constructor calls. The output makes the performance cost of value-based interfaces visible. A vector of Date pointers avoids those object copies in the demonstrated program, but changes the interface and lifetime responsibilities.

How Object-Oriented Software Design in C++ covers it

How deep it goes
Shows a member-by-member implementation and traces repeated runtime calls, while deferring deeper copy semantics.
Examples
Uses an instrumented Date class, vector append and insertion, and a noncopyable ExecutivePass singleton.
What you can do after
Diagnose unexpected copying by instrumenting special members and evaluate when copying must be disabled.
How it connects
Connects copy constructors with destructors, copy assignment operators, move constructors, move assignment operators, vectors, and the Singleton design pattern.

Also explained in

Compare how 2 books explain copy constructor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.