Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use =default for default ctors with a member initializer list

Consider the following class:

class Foo {
  int a, b;
public:
  Foo() : a{1}, b{2} {} // Default ctor with member initializer list
  //Foo() : a{1}, b{2} = default; // Does not work but why?
};

(Edit: because it was mentioned in a couple of answers - I'm aware of in-class member initializiers, but that's not the point here)

I think the second ctor definition would be more elegant and fit better into modern C++ code (see also why you should use =default if you have to be explicit about using the default semantics). However, no common compiler seems to accept it. And cppreference is silent about it.

My first thought was that a member initializer list in a way changes the "default semantics" as explained in the linked FAQ, because it may or may not default-construct members. But then we would have the same problem for in-class initializers, just that here Foo() = default; works just fine.

So, why is it disallowed?

like image 599
andreee Avatar asked Jun 05 '19 12:06

andreee


2 Answers

= default; is an entire definition all on its own. It's enforced, first and foremost, grammatically:

[dcl.fct.def.general]

1 Function definitions have the form

function-definition:
    attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt function-body

function-body:
    ctor-initializeropt compound-statement
    function-try-block
    = default ;
    = delete ; 

So it's either a member initializer list with a compound statement, or just plain = default;, no mishmash.

Furthermore, = default means something specific about how each member is initialized. It means we explicitly want to initialize everything like a compiler provided constructor would. That is in contradiction to "doing something special" with the members in the constructor's member initializer list.

like image 158
StoryTeller - Unslander Monica Avatar answered Nov 15 '22 22:11

StoryTeller - Unslander Monica


Doing a{1}, b{2} means you no longer can specify it as default. A default function per [dcl.fct.def.default]/1 is defined as

A function definition whose function-body is of the form = default; is called an explicitly-defaulted definition.

And if we check what a function-body is in [dcl.fct.def.general]/1 we see that it contains a ctor-initializer which is a mem-initializer-list

This means you can't initialize members if you want a default definition provided by the compiler.

What you can do to work around this is to specify the default values in the class directly, and then declare the constructor as default like

class Foo {
  int a{1}, b{2};
public:
  Foo() = default;

};
like image 20
NathanOliver Avatar answered Nov 15 '22 21:11

NathanOliver