Why does this code work? I expected this to fail because of breaking of one of the basic C++ rules:
#include <iostream>
using namespace std;
struct A {
A() { cout << "ctor A" << endl; }
void doSth() { cout << "a doing sth" << endl; }
};
struct B {
B(A& a) : a(a) { cout << "ctor B" << endl; }
void doSth() { a.doSth(); }
A& a;
};
struct C {
C() : b(a) { cout << "ctor C" << endl; }
void doSth() { b.doSth(); }
B b;
A a;
};
int main()
{
C c;
c.doSth();
}
https://wandbox.org/permlink/aoJsYkbhDO6pNrg0
I expected this to fail since in C's constructor, B is given a reference to object of A when this A object has not yet been created.
Am I missing something? Does the rule of order of initialization being the same as the order of fields not apply for references?
EDIT: What surprises me even more is that I can add a call to "a.doSth();" inside B constructor and this will also work. Why? At this moment the A object should not exist!