My problem is based on typical diamond hierarchy, but is not a typical diamond problem.
class Interface
{
public:
int value;
// SomeBigData &data;
Interface(int _value = 0) : value(_value) {};
virtual void function1() = 0;
virtual void function2() = 0;
};
class ImpOne : public virtual Interface
{
public:
void function1() { ++value; }
};
class ImpTwo : public virtual Interface
{
public:
void function2() { --value; }
};
class Device : public ImpOne, public ImpTwo
{
public:
Device() : Interface(7) {};
};
There is an abstract interface defining many function (the example above is simplified). Then there are implementation classes that implement only a few of these functions at a time. And finally, there are a non-abstract classes, like class Device above, implementing the whole interface by combining several implementation classes together.
Now, the problem is this:
There is an integer element in Interface class that gets initialized by class Device and is shared among implementation classes, so far so good. But if I remove the = 0
from Interface(int _value = 0)
constructor, the whole system collapses because I am missing default constructor for Interface class, which is a bit odd, because it never gets called.
Why does that bother me? As suggested in code, the Interface class needs to contain reference to complex data structure (not owned by the class), which is than shared among all derived implementation classes. It is however neither sensible nor possible to specify a default value for a reference.
So the question is:
How do I correctly initialize an Interface class (reference) element such as SomeBigData &data
suggested in code, where I can’t specify default value for default constructor (which never gets called anyway)? Or am I doing something wrong?