0
class WithCC { // With copy-constructor public: // Explicit default constructor required: WithCC() {} WithCC(const WithCC&) { cout << "WithCC(WithCC&)" << endl; } }; class WoCC { // Without copy-constructor string id; public: WoCC(const string& ident = "") : id(ident) {} void print(const string& msg = "") const { if(msg.size() != 0) cout << msg << ": "; cout << id << endl; } }; class Composite { WithCC withcc; // Embedded objects WoCC wocc; public: Composite() : wocc("Composite()") {} void print(const string& msg = "") const { wocc.print(msg); } }; 

I'm reading thinking in c++ chapter 11 default copy-constructor. For the above code, the author said: "The class WoCC has no copy-constructor, but its constructor will store a message in an internal string that can be printed out using print( ).This constructor is explicitly called in Composite’s constructor initializer list".

Why the WoCC constrcutor must be explicitly called in Composite's constructor?

1
  • WoCC does have a copy constructor. Since you didn't declare one, it gets an implicitly declared copy constructor. Commented Feb 23, 2013 at 18:27

1 Answer 1

1

You can happily leave out the explicit construction because wocc will be implicitly default constructed. A default constructor is one that takes no arguments. WoCC has a default constructor because the constructor that takes a string has a default value for that string.

The constructor only needs to be called explicitly if you want to pass a specific string, as is happening in this case.

However, if the argument did not have a default value (remove = ""), then you would indeed have to explicitly call the correct constructor in Composose. That's because defining any of your own constructors stops the compiler from implicitly generating a defaulted default constructor. If it has no default constructor, then you need to make sure the correct one is called for the wocc member.

Also, WoCC does indeed have a copy constructor. The compiler generates an implicit copy constructor if you don't define one (and it only defines it as deleted if you provide a move constructor).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.