The copy constructor creates a new object by copying another object's resources. It takes a const& argument:
class Buffer {
public:
Buffer(int n) : size(n), data(new int[n]) {}
Buffer(const Buffer& other) : size(other.size), data(new int[other.size]) {
std::copy#include <algorithm>(other.data, other.data + size, data);
}
~Buffer() { delete[] data; }
int size;
int* data;
};The copy constructor is invoked when a new object is initialised from an lvalue:
Buffer a(10);
Buffer b = a; // Copies a to b.The copy constructor can be deleted to prevent usage:
class Buffer {
public:
Buffer(const Buffer&) = delete;
};
Buffer b = a; // ERROR.The copy constructor can be defaulted to let the compiler generate it:
class Buffer {
public:
Buffer(const Buffer&) = default;
};Warning
The compiler-generated copy constructor performs shallow copying, so any deep copying must be done manually.
Dan