You cannot redefine them separately; you must redefine both points:
struct Interface1 { virtual void Name() = 0; }; struct Interface2 { virtual void Name() = 0; }; struct RealClass : Interface1, Interface2 { virtual void Name(); };
You can simulate an individual override with intermediate base classes:
struct RealClass1 : Interface1 { virtual void Name() { printf("Interface1 OK?\n"); } }; struct RealClass2 : Interface2 { virtual void Name() { printf("Interface2 OK?\n"); } }; struct RealClass : RealClass1, RealClass2 { virtual void Name() {
Also, you are using reinterpret_cast incorrectly, you should have:
int main() { RealClass rc; // no need for dynamic allocation in this example Interface1& one = rc; one.Name(); Interface2& two = dynamic_cast<Interface2&>(one); two.Name(); return 0; }
And here rewrite CRTP , which may be what you want (or not):
template<class Derived> struct RealClass1 : Interface1 { #define self (*static_cast<Derived*>(this)) virtual void Name() { printf("Interface1 for %s\n", self.name.c_str()); } #undef self }; template<class Derived> struct RealClass2 : Interface2 { #define self (*static_cast<Derived*>(this)) virtual void Name() { printf("Interface2 for %s\n", self.name.c_str()); } #undef self }; struct RealClass : RealClass1<RealClass>, RealClass2<RealClass> { std::string name; RealClass() : name("real code would have members you need to access") {} };
But note that here you cannot call Name on RealClass now (with virtual sending, for example rc.Name() ), you must first select the base. Macro photography is an easy way to clear CRTP broadcasts (usually access to membership is much more common in the CRTP database), but it can be improved . There's a short discussion of virtual sending in one of my other answers , but it is certainly better if anyone has a link.
Roger Pate Jan 05 2018-10-10T00: 00Z
source share