3

Does this conform to the standard?

class Foo {
    Bar m_bar;
    Bar * m_woo;
public:
    Foo() : m_bar(42, 123), m_woo(&m_bar) { }
};
Nick Strupat
  • 4,928
  • 4
  • 44
  • 56

1 Answers1

4

It is correct. What is not correct is dereferencing that pointer before that particular subobject has been fully initialized.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • 2
    And subobjects are initialized in the order they are declared, not the order they appear in the initialization list. So even if the constructor were written as `Foo() : m_woo(&m_bar), m_bar(42, 123) { }`, `m_bar` would be constructed before `m_woo` is. – Dennis Zickefoose May 04 '10 at 17:25
  • Right @Dennis, but even if the order was the opposite, with the given example it would still be correct, as you can initialize a pointer or reference to the yet uninitialized member. The problem would be if within the initialization list `m_woo` was dereferenced before `m_bar` was initialized. – David Rodríguez - dribeas May 04 '10 at 17:48
  • No, I understand. I was clarifying in case he does need to dereference `m_woo` for some other member. My intuition says the initialization takes place in the order given by the initializer list, and that intuition is wrong. – Dennis Zickefoose May 04 '10 at 18:16
  • @Dennis: Nota bene: GCC warns if the initialiser list has a different order from the declarations. – Jon Purdy Oct 30 '10 at 21:25