Home > database >  Class reference member - Not an error in a class with synthesized constructor but error in user defi
Class reference member - Not an error in a class with synthesized constructor but error in user defi

Time:09-16

Below errors out. Understood.

class a {
   int b;
   int &c; // uninitialized
   a(int x): b(x) {}
};

Below uses synthesized constructor. Why no error below? How does the synthesized constructor initialize the reference or will it even do that? Reference has to be user initialized from what I understand.

class a {
   int b;
   int &c;
};

CodePudding user response:

The error in your first class comes here:

a(int x): b(x) {}  // error

This is because you've defined a constructor that doesn't initialize the reference member c. This is an ill-formed constructor, and so the compiler gives an error.

In the second class, the compiler will synthesize a constructor, so there's no error. However, that constructor is defined as deleted, and so you won't be able to create an object of this type.

a test1{};      // error
a test2{1, n};  // also error (assuming n is an int)

demo


So essentially, the error in the first case is that the class definition is ill-formed. In the second case, it's a well-formed class with a deleted constructor, which may be intentional.

  • Related