0

In my code I had an interface and its implementation:

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


};
class Impl : public Interface
{
public:
    virtual ~Impl() {}
    virtual void f() {
        // ...
    }
};

However one beautiful day I decided that I need to enrich my interface with a new method, so I created a derived interface:

class InterfaceExt : public Interface
{
public:
    virtual ~InterfaceExt() {}
    virtual void g() = 0;
};

Now I need an implementation of the new interface, but I would like to reuse the existing implementation of the old interface, so I tried to do something like this:

class ImplExt : public virtual InterfaceExt, public virtual Impl
{
public:
    virtual ~ImplExt() {}
    virtual void g() {
        // ...
    }
};

It seems reasonable, compiler should see that all methods from InterfaceExt are accessible in ImplExt. Unfortunately, it doesn't compile:

diamond.cpp:38: error: cannot declare variable 'a' to be of abstract type 'ImplExt' diamond.cpp:25: note: because the following virtual functions are pure within 'ImplExt': diamond.cpp:5: note: virtual void Interface::f()

Of course, I can always to something like

virtual void f() {
    Impl::f();
}

but in my real code I have a lot of methods, and doing this kind of thing would be quite tedious. I was hoping that there is a better solution.

Thanks for your comments!

grześ
  • 467
  • 3
  • 21
  • 1
    Have you modify InterfaceExt to `class InterfaceExt : public virtual Interface` ? – Jarod42 Apr 07 '16 at 13:21
  • You may be running into this problem: https://crazycpp.wordpress.com/2011/03/28/name-resolution-and-overloading/ – Edward Strange Apr 07 '16 at 13:34
  • 2
    Your approach is good, also correctly realized that this is a `diamond-problem`, the only issue is that you used `virtual inheritance` at the wrong place. `InterfaceExt` and `Impl` should derive virtually. – mcserep Apr 07 '16 at 13:36
  • Putting virutal to the right place solved the issue, thanks! – grześ Apr 07 '16 at 14:07

0 Answers0