Search code examples
c++oopoverridingabstract-classmultiple-inheritance

Is it possible to use a method from one parent class to implement an abstract method from another parent class?


I've got the following classes:

class ServoPart {
private:
    bool move() {
        /* move implementation for a singular servo */
    }
}

struct RoboPart {
    virtual void doJob() =0;
    virtual bool move() =0;
}

class Claw : public ServoPart, RoboPart {
private:
    void doJob() {/* implementation */}
}

class Arm : RoboPart {
private:
    ServoPart major, minor;

    void doJob() {/* implementation */}
    bool move() {/* implementation for two servos */}
}

Now, Arm works since it implements both, doJob and move. Claw however doesn't work because it would be an abstract class since it doesn't implement move (even though it has move from the base class). When I add bool move() override; to Claw, I get an undefined reference to `vtable for Claw' failure from the linker.

Is it possible to do this somehow? Or do I need to rename ServoPart#move to ServoPart#moveStep and call that from a function move in Claw?


Solution

  • The main problem here, is that all your methods are private, so no of them can be called from outside the defining class, not even from a subclass.

    Assuming that the blocking private: declarations can be removed, there is no problem in using a method from a superclass to implement a method from another superclass provided it is accessible, but the implementation must be explicit:

    class ServoPart {
    protected:
        bool move() {
            /* move implementation for a singular servo */
        }
    };
    
    class Claw : public ServoPart, RoboPart {
    private:
        void doJob() {/* implementation */}
        bool move() {
            return ServoPart::move();
        }
    };
    

    }