6

I have such code

class A
{
    A() = default;
};

class B
{
    B(); 
};

B::B() = default;

int main()
{
    A a{}; //1
    A a1;  //2
    B b{}; //3
    B b1;  //4
}

Lines 2, 3, 4 generates compilation error as expected. But line 1 works! Please explain

  1. Difference between lines 1 and 2? In my opinion both of them should use default constructor and generate the same error.
  2. Difference between constructors in A and B classes.
Cœur
  • 37,241
  • 25
  • 195
  • 267
Andrey Nekrasov
  • 456
  • 2
  • 12
  • 2
    Try this with several compilers. It looks like line 1 is treated as aggregate initialization (so no constructor is called!), but what constitutes an aggregate has been a matter of some change in the recent past. – Kerrek SB Jun 15 '17 at 14:33
  • Actually, I think `A` has always been an aggregate, even in C++11. The differences since have been when the class has default member initializers. – Kerrek SB Jun 15 '17 at 14:36
  • According to cppreference.com ([link](http://en.cppreference.com/w/cpp/language/default_constructor#Implicitly-declared_default_constructor)) the implicit default constructor is always inline and public, and `= default` forces the implicit default constructor to be generated (it isn't user provided). It would be nice to see what the standard actually says about this. – François Andrieux Jun 15 '17 at 14:36

0 Answers0