Search code examples
c++classc++11structdefault-constructor

ERROR: Cannot synthesize a Constructor for A


Hi i am trying to understand how constructors work in C++. For this i am using the following example:

class NoDefault
{
public:
  NoDefault (const std::string &){}

};

struct A
{               
  NoDefault my_mem;
};

struct B
{
  B ()
  {
  }             // error: no initializer for b_member
  NoDefault b_member;
};


These are the things i already know: i know that class NoDefault has no default constructor and struct B has a default constructor(that we defined explicitly). I also know that if we don't provide any constructor to a class then it will automatically generate a default constructor. So according to this a default constructor should be generated automatically for struct A So both struct A and struct B now should have their own default constructors. Now i am getting the error:

main.cpp: In constructor ‘B::B()’: main.cpp:23:5: error: no matching function for call to ‘NoDefault::NoDefault()’ B() {} // error: no initializer for b_member

My question is why there is not the same error in struct A? Doesn't struct A has its own version of synthesized default constructor? I guess in struct B we are getting error because when the compiler tries to default initialize b_member it cannot do so since class NoDefault has no default constructor and we have not used any initializer for b_member. But the same thing should happen to struct A. Why is there a difference between these two structs?


Solution

  • As described on cppreference the default constructor for A is declared.

    3 Implicitly-declared default constructor
    If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

    But in your small example it is not defined because it is never called/needed.

    4 Implicitly-defined default constructor
    If the implicitly-declared default constructor is not defined as deleted, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++11),

    If you try to call it (just add a A a;), then you'll get the error that you expect.