Question

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()?

Was it helpful?

Solution

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  
};

OTHER TIPS

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  
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top