Search code examples
c++c++11language-lawyerdefault-constructorctor-initializer

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?


Solution

  • = 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.