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.
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:
Boost’s utility eliminates repeated code.