I have a class hierarchy with a diamond structure and a base class without default constructor, since it has reference members.
The code looks as follows:
class Base
{
public:
Base( CustomType& obj ) : refObj_( obj ) {}
virtual ~Base() {}
private:
CustomType& refObj_;
};
class Left : public virtual Base
{
public:
Left() {}; // ERROR: Compiler requests calling Base's constructor
virtual void leftsMethod() = 0;
};
class Right : public virtual Base
{
public:
Right( CustomType& obj ) : Base( obj ) {}; // Compiles, but Base( obj ) never gets called here
virtual void rightsMethod() = 0;
};
class Bottom : public Left, public Right
{
public:
Bottom( CustomType& obj ) : Base( obj ), Left(), Right( obj ) {}
};
Edit: Added virtual base destructor (original code has it)
Note that Left and Right are pure virtual classes, i.e. under no circumstances their constructors would call Base's constructor. This is due to virtual inheritance, implying that the most derived class Bottom calls Base's constructor.
My question: Why do I nevertheless have to call Base's constructor in the initialization list of Left? I'd like to avoid this and to pass the reference directly from Bottom's constructor only to Base. (I'm using MSVC 2010s "half C++11" compiler.)
Is there another solution for this combination of virtual inheritance and references in the base class?
=0
to the declaration of an unrelated member function (i.e. toggling if that member function is pure virtual or not) to change how the compiler treatsLeft
s constructor (e.g. compiles the constructor definition if the function is pure virtual, but does not compile if the function is virtual but not pure). Although, AFAIK, it's not a formal requirement of the standardisation process, few developers - including those on the standardisation committee - like the idea of a change of code causing something unrelated to break. – Peter