Question

class WithCC { 
public:
  WithCC() {}
  WithCC(const WithCC&) {
    cout << "in WithCC's copy constructor" << endl;
  }
};


class Composite {
  WithCC withcc; // Embedded objects
public:
  Composite() {}
};

int main() {
  Composite c;
  Composite c2 = c;
} 

With the code above, withcc's copy constructor gets called and I get the output: in WithCC's copy constructor

But if I add a copy constructor to Composite like this...

class Composite {
  WithCC withcc; // Embedded objects
public:
  Composite() {}
  Composite(const Composite&) {
      cout << "in composite's copy constructor" << endl;
  }
};

withcc's copy constructor doesn't seem to get called because the output is: in composite's copy constructor

Why isn't withcc's copy constructor called here?

Was it helpful?

Solution 2

The copy constructor implicitly defined by the compiler performs a memberwise copy/move of its bases and members.

A user-defined copy-constructor defaault initializes subobjects of the derived class if their constructors were not called explicitly in the ctor-list.

So in your last code snippet you defined explicitly the copy constructor

  Composite(const Composite&) {
      cout << "in composite's copy constructor" << endl;
  }

but its ctor list is empty. So data member withcc will be default initialized.

I described this more detailed in my article

Implicitly defined copy constructor and explicitly defined copy constructor: what is the difference?

Though it is written in Russian but you will be able to read it using for example google service translare.

OTHER TIPS

In the first sample you omitted a copy constructor for Composite and hence C++ generated a default one for you. This default one essentially runs a field by field copy and hence was running the copy constructor of WithCC.

When you explicitly defined a copy constructor C++ does no magic. It is up to you to copy the fields as necessary. For example

Composite(const Composite& other) : withcc(other.withcc) {
      cout << "in composite's copy constructor" << endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top