Call default copy constructor from within overloaded copy constructor

Alan Turing picture Alan Turing · Sep 4, 2011 · Viewed 8.4k times · Source

I need to write a copy constructor that deep copies the contents of a std::shared_ptr. However, there are a bunch of variable int a, b, c, d, e; also defined in the class. Is there a way to generate the default copy constructor code (or call the default copy constructor) inside my new overloaded one.

Here is a code snippet with a comment that hopefully clarifies the issue.

class Foo {
public:
     Foo() {}
     Foo(Foo const & other);
     ...
private:
     int a, b, c, d, e;
     std::shared_ptr<Bla> p;
};

Foo::Foo(Foo const & other) {
    p.reset(new Bla(*other.p));

    // Can I avoid having to write the default copy constructor code below
    a = other.a;
    b = other.b;
    c = other.c;
    d = other.d;
    e = other.e;
}

Answer

Seth Carnegie picture Seth Carnegie · Sep 4, 2011

I always think that questions like this should have at least one answer quote from the standard for future readers, so here it is.

§12.8.4 of the standard states that:

If the class definition does not explicitly declare a copy constructor, one is declared implicitly.

This implies that when a class definition does explicitly declare a copy constructor, one is not declared implicitly. So if you declare one explicitly, the implicit one does not exist, so you can't call it.