1

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());
}
curiousguy
  • 8,038
  • 2
  • 40
  • 58
John
  • 6,433
  • 7
  • 47
  • 82

3 Answers3

2

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.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
1

You are very vague about what your real problem is, but to me it sounds as if you want to use inheritance just to get code reuse.
You should not do this. Have a look at this article.
To me it sound as if composition is more what you want. Create a member of your ComplicatedOne in your class Line and delegate the calls to this member. Then you don't need to inherit from it.

mkaes
  • 13,781
  • 10
  • 52
  • 72
0
    return Object::Equals(obj);

That cannot compile, because it is ambiguous: there are two Object base objects.

Also, conversion from Line* to Object* is ambiguous, and the ambiguity cannot be resolved to the second Object base class (in left to right base class order), so the second Object base does not serve any purpose except to create difficulties.

It is not clear what you are trying to do exactly: what does the ComplicatedOne class represent? Why do you inherit from it, if you are going to override every Object virtual function again?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
  • Though `ComplicateOne` contains `//Lots of funcs I don't want or need.`, it has still has its uses. – John Dec 29 '11 at 11:35