Delegate part of an interface to a subclass in C ++?

I have a relatively complex interface in my code and would like to delegate part of the implementation to another class without writing many forwarding functions in the implementation. See this simplified code example:

#include <stdio.h>

struct Interface {
    virtual void foo() = 0;
    virtual void bar() = 0;
    virtual ~Interface() {}
};

struct Delegate {
    virtual void foo()
    { printf("foo\n"); }
};


struct Impl : public Interface, private Delegate {
    // delegate foo to Delegate
    using Delegate::foo;

    void bar()
    { printf("bar\n"); }
};

int main() {
    Interface* i = new Impl();
    i->foo();
    i->bar();
    delete i;
    return 0;
}

Now g ++ complains that foo is not implemented in Impl. However, Impl has a very nice foo function, it just comes from another parent class. Why doesn't the compiler populate the vtable accordingly?

(Note: I know that a delegate could get an interface in this particular example. I would like to understand if functionality can be delegated without having to remove the delegate from the interface.)

+5
source share

No one has answered this question yet.

See similar questions:

thirteen
++ ?

:

4247
++
3076
++?
1455
int ++
732
++?
1

All Articles