Gu Yu Gu Yu - 9 months ago 36
C++ Question

C++ Primer questions: delegates to a default constructor

I have a question about an example & explanation at C++ Primer 5th, P.292, it is about how to use delegate constructors:

class Sales_data {
public:
//target constructor
Sales_data(std::string s, unsigned cnt, double price) :
bookNo(s), units_sold(cnt), revenue(cnt * price) { }
//delegate constructor that I have question on
Sales_data(std::istream &is): Sales_data() {read(is, *this)}
};


for explaining how this delegate constructor works,the book said:


It delegates to the default constructor , which in turn delegates to the three-argument constructor.


I was confusing about the explanation. I don't get why the delegate constructor delegates a default constructor first , then still need to delegates the target constructor.

For confirming my thought I did some experiments:

First, I have a thought that the target constructor will automatically generate a default constructor, because there is no default constructor declaration in the example code; And I know the default constructor is a must when I have my custom constructor. So I tried to compile the class with some simple test code here:

int main(int argc, char const *argv[]) {
Sale_data item1(std::cin);
print(std::cout, item1);
return 0;
}


and I got a error:

error: no matching function for call to Sale_data::Sale_data()


Then I added the
Sales_data() = default
, the program printed the correct result.

Next, I deleted my target constructor. However, the program still represents a same result as what I got from the step 2: looks like the default constructor did its job well.

Comparing with what the book explained, my experiment shows that the target constructor has no business with the delegate constructor, in my case. Would you please point out where am I wrong??

Thanks in Advance for your help!

Answer Source

First, I have a thought that the target constructor will automatically generate a default constructor, because there is no default constructor declaration in the example code;

There is a default constructor in the book. Just right after the three parameter target consturctor. Did you refer to the wrong code sample?

Sales_data(): Sales_data("", 0, 0) {}