0

I have a class with some constant pointers to objects. What is the sequence of execution of the const value constructors and when are they assigned? This may make more sense looking at the following code.

class Foo
{
public:
    Child2* const m_Child2;
    Child1* const m_Child1;

    Foo() : 
        m_Child1(new Child1(*this)),
        m_Child2(new Child2(*this))
    {}
};


class Child2
{
public:
    Child2(Foo& Parent)
    {
        Parent.m_Child1; 
            // this value is still `nullptr` even though it should
            // have been created before this constructor call
    }
}

Is it possible for the constructor of Foo::m_Child2 to access the constructed object Foo::m_Child1?

Russell Trahan
  • 783
  • 4
  • 34
  • The value of `Parent` in Child2 is not null. It can't be null because of `Foo& Parent`. – Russell Trahan Sep 03 '15 at 23:57
  • 3
    The fact you are asking this question indicates a flaw in your design. This is not good design. If you insist on continuing anyway, see [this answer](http://stackoverflow.com/a/1242845/1553090) – paddy Sep 03 '15 at 23:57
  • 2
    @paddy: The question isn't just about the order the members are constructed in; it's also about whether `new Child2(*this)` gets evaluated before `m_Child1` is constructed. –  Sep 03 '15 at 23:59
  • 2
    Aside: are you really sure you want the type of `m_Child1` to be `Child1 *const` rather than, say, `Child1` or if it really does need to be a pointer, `const std::unique_ptr const`? –  Sep 04 '15 at 00:01
  • Ah. Thanks paddy. That actually was the problem. The constructors are called in the sequence they appear in the definition of Foo--not the sequence in the constructor of Foo. I had them switched--didn't know the order mattered. – Russell Trahan Sep 04 '15 at 00:03
  • Good point on the `unique_ptr`, @Hurkyl. Without this, if the second `new` throws, then `m_Child1` will never be deleted. – paddy Sep 04 '15 at 00:07
  • I think with `-Wall`, gcc will give you a warning if your member initializers are in a different order than the members are declared in their class. Maybe other compilers can be made to do this too with the right options. –  Sep 04 '15 at 00:43
  • Please post a MCVE. In lieu of that, I guess you are writing `Foo f;` (or otherwise constructing a Foo) and then inspecting `Parent.m_Child1` during the constructor of the object for `new Child2(*this)` which initializes `m_child2`. So you are inspecting `m_child1` before `m_child1` has been initialized. – M.M Sep 04 '15 at 01:30

0 Answers0