Copy constructors

A copy constructor is a constructor which can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

# Notes

In many situations, copy constructors are optimized out even if they would produce observable side-effects, see copy elision.

# Example

struct A
{
    int n;
    A(int n = 1) : n(n) {}
    A(const A& a) : n(a.n) {} // user-defined copy constructor
};
 
struct B : A
{
    // implicit default constructor B::B()
    // implicit copy constructor B::B(const B&)
};
 
struct C : B
{
    C() : B() {}
private:
    C(const C&); // non-copyable, C++98 style
};
 
int main()
{
    A a1(7);
    A a2(a1); // calls the copy constructor
 
    B b;
    B b2 = b;
    A a3 = b; // conversion to A& and copy constructor
 
    volatile A va(10);
    // A a4 = va; // compile error
 
    C c;
    // C c2 = c; // compile error
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
CWG 1353C++98the conditions where implicitly-declared copy constructorsare undefined did not consider multi-dimensional array typesconsider these types
CWG 2094C++11volatile members make copy non-trivial (CWG issue 496)triviality not affected
CWG 2171C++11X(X&) = default was non-trivialmade trivial
CWG 2595C++20a copy constructor was not eligible if there isanother copy constructor which is more constrainedbut does not satisfy its associated constraintsit can be eligible in this case

# See also