I have a main class (MyClass) derived from MyBase. Also I have a Helper class (used by MyClass) derived from HelperBase (used by MyBase). Is there a way to initialize the Helper in the constructor initialization of MyClass and also pass the helper down to MyBase that takes a HelperBase as constructor argument? Something as follows:
EDIT: forgot to derive Helper from HelperBase (as mentioned in the comments) fixed that in the sample code
//-------------------------------------------
// HelperBase.h
class MyBase;
// HelperBase holds a ref to MyBase
class HelperBase {
public:
HelperBase(MyBase& i_ParentBase);
protected:
MyBase& m_ParentBase;
};
// HelperBase.cpp
HelperBase::HelperBase(MyBase& i_ParentBase)
: m_ParentBase(i_ParentBase)
{}
//-------------------------------------------
// Helper.h
class MyClass;
// Helper holds a ref to MyClass
class Helper : public HelperBase{
public:
Helper(MyClass& i_Parent);
protected:
MyClass& m_Parent;
};
//-------------------------------------------
// MyBase.h
// MyBase holds a ref to HelperBase
class MyBase {
public:
MyBase(HelperBase& i_HelperBase);
protected:
HelperBase& m_HelperBase;
};
// MyBase.cpp
MyBase::MyBase(HelperBase& i_HelperBase) : m_HelperBase(i_HelperBase)
{}
//-------------------------------------------
// MyClass.h
// MyClass holds and initializes an instance of Helper
class MyClass : public MyBase
{
public:
MyClass();
protected:
Helper m_Helper;
};
// MyClass.cpp
MyClass::MyClass()
: MyBase(m_Helper), // <-- this is the problem !!!
m_Helper(*this)
{}
//-------------------------------------------
// Helper.cpp
Helper::Helper(MyClass& i_Parent)
: HelperBase(i_Parent),
m_Parent(i_Parent)
{}
//-------------------------------------------