I want to implement the pure virtual methods from an interface using the implementation provided by an concrete class without having to call explicitly the method from the concrete class. Example:
class InterfaceA{
public:
virtual void foo() = 0;
};
class InterfaceB:public InterfaceA{
public:
virtual void bar() = 0;
};
class ConcreteA : public InterfaceA{
public:
virtual void foo(){}//implements foo() from interface
};
class ConcreteAB: public InterfaceB, public ConcreteA{
public:
virtual void bar(){}//implements bar() from interface
};
In this scenario, the compiler asks for a implementation of foo() in class ConcreteAB, because InterfaceB does not have it implemented and it inherited from InterfaceA.
There is a way to tell the compiler to use the implementation from ConcreteA without using a wrapper calling ConcreteA::foo()?
Make InterfaceA
a virtual base class.
class InterfaceB : public virtual InterfaceA {
public:
virtual void bar() = 0;
};
class ConcreteA : public virtual InterfaceA {
public:
virtual void foo(){}//implements foo() from interface
};
You need virtual inheritance .
Interface A, at the top of the hierarchy, should be inherited virtually by all immediate subclasses.
class InterfaceB:public virtual InterfaceA{
public:
virtual void bar() = 0;
};
class ConcreteA : public virtual InterfaceA{
public:
virtual void foo(){}//implements foo() from interface
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.