ERROR: Cannot synthesize a Constructor for A

Viewed 75

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?

2 Answers

So according to this a default constructor should be generated automatically for struct A

... when it needs to be generated.

If you actually attempt to create an instance of it, you will discover that it won't work, either. If you were to attempt to declare an instance of A, the compiler will attempt to generate one, and fail.

In the case of B, you are defining an explicit constructor, and since it fails to explicitly construct it's b_member, the compiler attempts to default-constructor it, and fails because it does not have a default constructor.

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.

Related