Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a code like this. My derived class man, may not properly have a member fu

ID: 659141 • Letter: I

Question

I have a code like this. My derived class man, may not properly have a member function declared pure virtual higher up the hierarchy. eg. WagTail here

class mammal{
public:
    virtual void WagTail() = 0;
    virtual void BreastFeed() { };
    ~mammal();
};

class Terrestrials : public mammal{
public:
    virtual void sunbathe() = 0;
};

class cat : public Terrestrials {
    void sunbathe() override final {
        cout << "My owner made me stand in the sun";
    }
    void WagTail() override final   {
        cout << "Wagging Tail";
    }
};

class Man : public Terrestrials {
    void sunbathe() override final {
        cout << "Life is good!";
    }
    void WagTail() override final   {
        // Wait, Wha??? ERROR!!!!
    }
};
What is the best way to fix a mistake like this without rewriting the entire hierarchy?

Explanation / Answer

The fundamental problem is that a pure virtual function was added very high in a class hierarchy which not all conceivable subclasses can plausibly support. This is why one should be very careful defining deep class hierarchies. I see a couple approaches.

One approach is to simply provide an empty implementation of WagTail for the Man class. Hopefully this won't break anything. And after all, primates generally have tails, only for people they have withered away to an internal coccyx (tailbone) because they provided no benefit. And some people are in fact born with "tails".

Another is to move tail-ness into a separate class, really just an interface, and have most Terrestrials inherit from that. This way other classes, like Reptiles and Fish, can also have tails and a WagTail method. In general, multiple inheritance of interfaces is preferable to deep class hierarchies.

Historical Note: Back in the 1980s and early 1990s, before there was Java and C++ compilers did not widely support multiple inheritance, deep class hierarchies were quite common. Microsoft's MFC was quite deep, as was Apple's MacApp.