4

Here is a code snipped which is not compilable under gcc 10.2.

struct Document {
   int id;

   Document() = default;
};

int main()
{
   const Document test;

   return 0;
}

Is it an expected behaviour? I believe that default constructor must initialize all internal members to default value and since int is a primitive type it must be 0 (at least in 99% of cases). Am I wrong?

Here is an output :

‘const struct Document’ has no user-provided default constructor
Dmitry
  • 1,912
  • 2
  • 18
  • 29
  • 2
    You might want to add the compiler warning to your question. – Ole Wolf Nov 23 '20 at 13:24
  • 5
    when something does not compile: read the error message. Please include it in the question (though the message is rather clear) – 463035818_is_not_an_ai Nov 23 '20 at 13:25
  • 2
    "_I believe that default constructor must initialize all internal members to default value_" Why do you believe that? – Algirdas Preidžius Nov 23 '20 at 13:25
  • fwiw this is a case where gcc's message is more helpful than clangs: https://godbolt.org/z/ThjhKs – 463035818_is_not_an_ai Nov 23 '20 at 13:26
  • thats not the complete error message (if it is, I strongly suggest to use a better compiler) – 463035818_is_not_an_ai Nov 23 '20 at 13:27
  • Did you read the notes under said error message, when compiling with gcc 10.2? "_note: constructor is not user-provided because it is explicitly defaulted in the class body and the implicitly-defined constructor does not initialize 'int Document::id'_"? – Algirdas Preidžius Nov 23 '20 at 13:29
  • Thanks guys for all your comments and links. The main question for me - why default ctor declared the way I did is not a "user-declared" ? What is the meaning of "=default" in this case? – Dmitry Nov 23 '20 at 13:56
  • @Dmitry this might help https://stackoverflow.com/questions/20828907/the-new-syntax-default-in-c11 – drompix Nov 23 '20 at 13:59
  • @Dmitry it is user-declared but not user-defined. Its not really relevant for your question. I don't know why this was brought up. The duplicate that you can find on top should help you to understand why your code didnt work – 463035818_is_not_an_ai Nov 23 '20 at 14:00
  • @idclev463035818 thanls, just sorted out using the link in duplicate( I've done tons of experiments). The second answer is more useful from my point of view. I love and hate c++ =))) – Dmitry Nov 23 '20 at 14:25

0 Answers0