Home > Back-end >  Overriding a virtual function but not a pure virtual function?
Overriding a virtual function but not a pure virtual function?

Time:12-09

I'm attempting to derive a class C from two classes, A and B; after reading this answer, I attempted to write using B::<function> in order to override a pure virtual function in A with the implementation in B.

However, the approach in that answer does not work for pure virtual functions; in that case, I found that I needed to be more explicit. So evidently using can resolve ambiguity, but it can't introduce an implementation? I was just hoping to better understand what is going on here.

struct A {

    // this would result in ambiguity:
    //virtual void e(void) const {}   // ERROR: member 'e' found in multiple base classes 

    // resolving ambiguity with 'using'
    virtual void f(void) const {}     // OK

    // this would result in an unimplemented method:
    //virtual void g(void) const = 0; // ERROR: variable type 'C' is an abstract class

    // *** why doesn't this work? ***
    //virtual void h(void) const = 0; // ERROR: variable type 'C' is an abstract class

    // resolving ambiguity by explicitly defining what I want
    virtual void i(void) const = 0;   // OK
};
struct B {    
    void e(void) const {}
    void f(void) const {}
    void g(void) const {}
    void h(void) const {}
    void i(void) const {}
};
struct C : public A, public B {
    using B::f;                    // sufficient to pin down 'f'
    using B::h;                    // not sufficient to pin down 'h'
    void i(void) const { B::i(); } // sufficient to pin down 'i'
};
int main() {
    C X;
    X.e();
    X.f();
    X.g();
    X.h();
    X.i();
}

CodePudding user response:

I attempted to write using B::<function> in order to override a pure virtual function in A with the implementation in B.

You misunderstood. It is not possible to override a function this way. All that using B::h; does: it introduces B::h into the scope of struct C, so that X.h(); in main() becomes equivalent to X.B::h();. So, A::h() remains pure virtual, thus you cannot instantiate struct C.

  • Related