Search code examples
c++inheritancevirtual

Implementation of pure virtual function via inheritance


I have the following situation:

class Fork {
    public:
        virtual void use() = 0;
};

class Spoon {
    public:
        virtual void use() = 0;
};

class SilverSpoon : public Spoon {
    public:
        virtual void use() { }
};

class SilverSpork : public SilverSpoon, public Fork {
    public:
        using SilverSpoon::use;
};

I was hoping that the pure virtual function Fork::use would be defined by SilverSpoon::use in SilverSpork. However, I get

error: cannot declare variable ‘spork’ to be of abstract type ‘SilverSpork’
note:  because the following virtual functions are pure within ‘SilverSpork’:
note:  virtual void Fork::use()

Is there a way to solve this without having to add

virtual void use() {
    SilverSpoon::use();
}

to SilverSpork?


Solution

  • There's no inherent connection between Fork and Spoon, and the fact that they both have a virtual function named use doesn't make one. However, if you add a new class, say, Utensil that defines a pure virtual function use(), and derive both Fork and Spoon from it as a virtual base, you've got a connection. With that, the class SilverSpork will pick up the implementation of SilverSpoon::use as the overrider for use in its direct base Fork. This is known as "dominance".

    class Utensil {
    public:
        virtual void use() = 0;
    };
    
    class Spoon : public virtual Utensil {
    public:
        virtual void use() = 0; // or can omit this, relying on Utensil
    };
    
    class Fork : public virtual Utensil {
    public:
        virtual void use() = 0; // or can omit this, relying on Utensil
    };
    
    class SilverSpoon : public Spoon {
    public:
        void use() { }
    };
    
    class SilverSpork : public SilverSpoon, public Fork {
    }; // OK: SilverSpoon::use overrides Fork::use