views:

55

answers:

3

It is possible to pass uninitialized object to a parent class like in the following example

class C
{
    public:
        C(int i): 
            m_i(i)
        {};

        int m_i;
}

class T
{
    public:
        T(C & c):
            m_c(c)
        {
        };

        C & m_c;
};


class ST : public T
{
    public:
        ST():
            T(m_ci),
            m_ci(999)
        {
        };

        C m_ci;
};

In class T constructor, c is a reference to uninitialized object. If class T were using c object during construction, this would possibly lead to an error. But since it's not, this compiles and works fine. My question is - does it brake some kind of paradigm or good design directives? If so, what are the alternatives, because I found it useful to allocate an object required by parent in a subclass.

On a side note, I wonder why it's not possible to change initialization order, so that base class constructor would be called after initialization of some members.

+2  A: 

I've seen this a lot, and many compilers will warn. It's ok if the T constructor never dereferences the c reference.

If you don't want the warning, you need to do two stage construction. Make a protected Init(C&) method in T, and then call it in the ST constructor body -- unfortunately m_c will need to be a pointer to do that (since references can't be reassigned to another object)

Lou Franco
+2  A: 

You can, but you get undefined behavior.

In Boost's utilities, you'll find the base-from-member idiom created by R. Samuel Klatchko. Basically, you make a private base in the place of the private member. This base gets initialized first, and you can use it for other bases:

// ...

class C_base
{
public:
    C_base(int i) :
    m_ci(i)
    {}

    C m_ci;
};


class ST :
    private C_base
    public T
{
    public:
        ST() :
            C_base(999),
            T(m_ci),
        {
        };
};

Boost's utility eliminates repeated code.

GMan
+2  A: 

Passing a reference or pointer to something uninitialized is technically perfectly OK.

But the reason you ask is probably that you think that something easily can go wrong, that through some chain of calls one may inadvertently access the object before it's been initialized. And I think that's a valid concern. And there's another thing that can go wrong, namely that code in base class T can now possibly invalidate the class invariant of ST by directly changing a data member of ST instance...

So, I think it's a bit risky.

Regarding initialization order, C++ is based on the idea of constructing from parts up, in a hierarchy. If a constructor throws then completely constructed things are destructed, automatically. This would be more difficult or less efficient with more arbitrary construction order.

Cheers & hth.,

Alf P. Steinbach