Dardai Dardai - 1 month ago 13
C++ Question

C++ primer says that we can use initializer list for "=default" constructors

struct SalesData {

SalesData() = default;
SalesData(const string&s) : bookNo(s) {}

string bookNo;
unsigned copies_sold = 0;
double revenue = 0;
};


While discussing default constructors, primer says we can use the keyword "=default" to make a constructor default just like code above. That keyword can appear with the declaration inside the class, or with the definition outside the class.
If the compiler can't use in-class initializers, we can use initializer list just like the second constructor.

But what's the format?

First I tried to use initializer list directly:

SalesData() = default:bookNo(""), copies_sold(1), revenue(2){};


But it can't work, the compiler says there shouldn't be a colon afer "default".

Then I tried to declare the constructor with "=default" in class and define it outside, without using the initializer list:

struct SalesData {
SalesData() = default;
/*...*/}

SalesData::SalesData() {
bookNo = "";
copies_sold + 0;
revenue = 0;
}


The compiler says it's an error of redefinition.
Then I moved the keyword outside, which the primer says is supposed to be ok:

struct SalesData {
SalesData();
/*...*/}

SalesData::SalesData()=default {
bookNo = "";
copies_sold + 0;
revenue = 0;
}


It still failed, the compiler said there should be a semicolon behine the "default".

I've googled for similar questions, but nothing found.


  1. How could the "=default" and initializer list work together?

  2. How should I use the "=default" outside the class body?


Answer

In certain situations the compiler automatically generates special functions like the default ctor for you. =default is a way to tell the compiler explicitly to generate the function even in a situation where that would not happen automatically.

The point is: You either implement the function yourself as usual or you =default it. You cannot do both for the same function. The only way to influence what the compiler generates is via default initializers like your double revenue = 0;

Compiler generated implementations are available for the default ctor, copy ctor, copy assignment, move ctor, move assignment and destructor. See this answer for more details. SalesData(const string&) is neither of those, so it cannot be =defaulted.

Comments