default copy constructor

(thing) by ariels Sun Mar 04 2001 at 12:13:49

By default, the C++ compiler generates a copy constructor for every class. This default copy constructor copies all members (using their copy constructors, of course). For example, in a class

class Z {
  private:
    X x;
    Y y;
  public:
    // define stuff, but don't define Z Z(const Z& z)
    // ...
};
which does not define any copy constructor, the compiler supplies a default copy constructor which behaves like
Z::Z(const Z& z) : x(z.x), y(z.y)
{
  // nothing else to do
}
This would call the copy constructor X::X(const X&) and Y::Y(const Y&). This seemingly infinite nesting of default copy constructors is interrupted when a primitive type (e.g. char or double) is copied: these semantics are hard-coded into the language.

Note that the default copy constructor's semantics extend those of copying structs in C.

Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.