1

How does this code compile?

struct B {
    int a;  
};

 
class A
{
  B& b = b;
};

 

int main() {
  A a;
}

My understanding was that that reference had to be initialized? It is initialized but to itself? How does this code work and what is the reference of B initialized to?

cjds
  • 8,268
  • 10
  • 49
  • 84
  • 1
    The `b` is fully defined at the `=`, where the initializer starts. So `b` can be *used* at that point, but of course not read from until it is fully initialized. This is not much different from `int i = i;`, which has the same problem. – BoP Jul 18 '22 at 18:33
  • 1
    In C++, there are many syntactically valid constructs which are semantically ill formed, and do not require a diagnostic. I categorize these kinds of programmer errors as "Doctor, it hurts when I write this bad code." And the doctor says, "You know it's bad code. Don't write that bad code." – Eljay Jul 19 '22 at 13:50

0 Answers0