default copy constructor

sourabh912 picture sourabh912 · Sep 25, 2012 · Viewed 73.4k times · Source

Can the (implicit)default copy constructor be called for a class that has already user-defined constructor but that is not the copy constructor?

If it is possible then, suppose we define the copy constructor for the class explicitly, now can the (implicit)default constructor be called?

Answer

James Kanze picture James Kanze · Sep 25, 2012

First, let's clarify our vocabulary a bit. A default constructor is a constructor which can be called without any arguments. A copy constructor is a constructor which can be called with a single argument of the same type. Given this, a "default copy constructor" would be a constructor with a signature something like:

class MyClass
{
public:
    static MyClass ourDefaultInstance;
    //  default copy constructor...
    MyClass( MyClass const& other = ourDefaultInstance );
};

Somehow, I don't think that this is what you meant. I think what you're asking about is an implicitly declared or an implicitly defined copy constructor; a copy constructor whose declaration or definition is provided implicitly by the compiler. The compiler will always provide the declaration unless you provide a declaration of something that can be considered a copy constructor. Providing other constructors will not prevent the compiler from implicitly declaring a copy constructor.

This is different from the default constructor—any user defined constructor will prevent the compiler from implicitly declaring a default constructor. This means that if you have a user defined copy constructor, the compiler will not implicitly declare a default constructor.

The second important point is that you do not call constructors. The compiler calls them in certain well defined contexts: variable definition and type conversion, mainly. The compiler can only call constructors that are declared (including those that are implicitly declared). So if you have a user defined constructor (copy or otherwise), and do not define a default constructor, the compiler cannot call the constructor except in contexts where it has arguments to call it with.

To summarize what I think your questions are: the compiler will provide an implicit copy constructor even if the class has other user defined constructors, provided none of those constructors can be considered copy constructors. And if you provide a user defined copy constructor, the compiler will not provide an implicitly declared default copy constructor.