dimanche 21 février 2021

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?

Aucun commentaire:

Enregistrer un commentaire