Tom Davies
Tom Davies

Reputation: 2446

Multiple inheritance, inheriting an interface and an implementation

Is it possible inherit both an interface and an implementation mixin in the same class? Something like this:

class Interface
{
public:
    virtual void method()=0;
};

class Component
{
public:
    void method(){ /*do something*/};
};

class MyClass : public Interface, public Component
{};

...
...
Interface* p = new MyClass(); p.method();

The idea being that the pure virtual function inherited from Interface is implemented in MyClass through its inheritance of Component. This doesn't compile; I need to to do this:

class MyClass : public Interface, public Component
{
 public:
    void method(){Component::method();} override
 };

Is it possible to somehow avoid the explicit override and delegation to Component, perhaps by using templates somehow?

Upvotes: 1

Views: 111

Answers (1)

Martin J.
Martin J.

Reputation: 5108

If you want to avoid the explicit override and delegation to the component, there is no way around inheriting some kind of Interface-derived class that does this binding, because what you want to call ahas to end up in your derived class's vtable.

I guess you could make it work with a diamond-like inheritance structure and virtual inheritance, but it's not exactly pretty:

class Interface
{
public:
    virtual void method()=0;
};

class Component: virtual public Interface
{
public:
    virtual void method(){ /*do something*/};
};


class MyClass : virtual public Interface, private Component
{
public:
    using Component::method;
};

Usual disclaimer: virtual inheritance is expensive

I have tried to find something better using templates, but I don't think there's a way to bind the component method to the virtual method without having having either the component inherit from the interface, or having to write binding code by hand.

Upvotes: 2

Related Questions