Search code examples
c++inheritancemultiple-inheritanceaccess-specifier

C++ Multiple inheritence, base class visibility and the dreaded diamond. Re-exposing ancestor base class as public?


I need to abstract away a lot of the interface from a base class by making it protected, but I also need public access to a simple ancestor class Object. Can I negotiate the dreaded diamond without write/edit access to these ancestors and still present only a basic API but make Object's API public again?

class Object {
    virtual bool  Equals (const Object &obj) const;
    virtual int  GetHashCode (void) const;
};

class ComplicatedOne : public Object {
    //Lots of funcs I don't want or need.
};

class Line : protected ComplicatedOne, public Object {
    //Some funcs of ComplicatedOne get re-implemented or called by alias here
public:
    virtual bool Equals(const Object &obj) const {
        return Object::Equals(obj);
    }
    virtual int GetHashCode() const {
        return Object::GetHashCode();
    }
};

class Array {
    void Add (Object &obj);
    Object *GetAt (int i);
};

main() {
    Array a;
    a.Add(new Line());
}

Solution

  • You could use composition.

    You can hold an instance of ComplicatedOne as a member, and expose what you need.

    This way you can keep it protected, but will never have a Diamond situation.

    Besides, If ComplicatedOne is an Object, so Line is an Object by inheritance, so you don't need to inherit again.