dimanche 4 octobre 2015

Force member variable to be constructed before base class

I'm currently facing following scenario:

class foo 
{
public:
    foo ( /* some parameters */ );
};

class bar
{
public:
    bar ( foo & f );
};

// both foo and bar are 3rd party

class base
{
public:
    base ( foo & f ) : m_bar ( f ) {}

private:
    bar m_bar;
};

class derived : public base
{
public:
    derived ( foo & f ) : base ( f ) {}
};

class derived2 : public base
{
public:
    derived2 () : base ( /* well ... */ ) {} 

private:
    foo m_foo;
};

As you can see, foo and bar were designed to be used like this:

foo f ( /* some parameters */ );
bar b ( f );

However, I want my wrapper classes to be standalone if needed, and derived2 needs to be. But, derived2::m_foo cannot be just passed to base while its uninitialized.

So my question is: Is there a way to force derived2::m_foo to construct before base ?

The only solution I came up with myself is this:

class derived2_foo
{
protected:
    foo m_foo;
};

class derived2 : public base, public derived_foo
{
public:
    derived2 () : derived_foo (), base ( m_foo ) {}
};

Which should be valid code ( I'm free to be proven wrong ), but I'm not quite sure if I want to like that solution. So I'm here to fish for other ideas.

Aucun commentaire:

Enregistrer un commentaire