I have this class hierarchy in C++:
class ISegmentReader
{
public:
virtual void readCacheFromDb() = 0;
//...
};
class ISegmentManager: public ISegmentReader
{
//readCacheFromDb not redeclared
//...
};
class SegmentReader: public ISegmentReader
{
public:
void readCacheFromDb() override final;
};
class SegmentManager: public ISegmentManager, public SegmentReader
{
//readCacheFromDb not redeclared
//...
};
int main()
{
SegmentManager manager;
}
I would expect to be able to use SegmentReader::readCacheFromDb
implicitly in SegmentManager
. However, whenever I try to compile, I get:
... invalid new-expression of abstract class type ‘SegmentManager’ ...
because the following virtual functions are pure within ‘SegmentManager’
...
ISegmentReader::readCacheFromDb()’
virtual void readCacheFromDb() = 0;
Any way I can get around this without redeclaring/reimplementing:
SegmentManager::readCacheFromDb(){
SegmentReader::readCacheFromDb();
}
Many thanks
You might want to use the virtual inheritance so ISegmentReader
is a single instance in the SegmentManager
storage layout.
SegmentManager | ISegmentManager | SegmentReader | ISegmentReader
Instead of
SegmentManager | [ISegmentManager | ISegmentReader] | [SegmentReader | ISegmentReader]
https://godbolt.org/z/6qb478q43
class ISegmentReader {
public:
virtual void readCacheFromDb() = 0;
};
class ISegmentManager : public virtual ISegmentReader {};
class SegmentReader : public virtual ISegmentReader {
public:
void readCacheFromDb() override final {};
};
class SegmentManager : public ISegmentManager, public SegmentReader {};
int main() {
SegmentManager manager;
}