The following header and implementation files combines all three concepts but won't compile:
$ cat a.h
#include <memory>
class Base {
protected:
class BaseImpl;
std::shared_ptr<BaseImpl> pImpl;
Base(BaseImpl* impl)
: pImpl{impl}
{}
public:
virtual ~Base()
{}
virtual void func() =0;
};
class Der : public virtual Base {
private:
class DerImpl;
DerImpl* getPimpl() const noexcept;
public:
Der();
virtual ~Der()
{}
void func();
};
$ cat a.cpp
#include "a.h"
class Base::BaseImpl {
};
class Der::DerImpl : public virtual Base::BaseImpl {
public:
void func() {}
};
Der::Der()
: Base{new DerImpl()}
{}
Der::DerImpl* Der::getPimpl() const noexcept {
return static_cast<DerImpl*>(pImpl.get());
}
void Der::func() {
getPimpl()->func();
}
$ g++ --std=c++11 -c a.cpp
a.cpp: In member function ‘Der::DerImpl* Der::getPimpl() const’:
a.cpp:16:45: error: cannot convert from base ‘Base::BaseImpl’ to derived type ‘Der::DerImpl’ via virtual base ‘Base::BaseImpl’
return static_cast<DerImpl*>(pImpl.get());
^
Would you please tell me what's wrong, why, and how I might have separate declaration and definition files with the Pimpl idiom and multiple virtual inheritance.