0

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)
{}
//-------------------------------------------
Robin Holenweger
  • 321
  • 3
  • 14

1 Answers1

0

In the end it turned out the code works as above. There was a hidden/not so obvious naming convention clash that made the thing not compiling as expected (and the compile error did not reveal that at first sight). Sorry for that.

Robin Holenweger
  • 321
  • 3
  • 14