3

I need to cast a class to its protected base:

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

class Line : protected ComplicatedOne {
    //Some funcs of ComplicatedOne get re-implemented or called by alias here
};

class Array {
    void Add (Object &obj);
};

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

I need to add a Line to an Array but the Object base is not visible. Should I re-impliment its methods publicly or is there an implicit cast operator I could override?

John
  • 6,433
  • 7
  • 47
  • 82

2 Answers2

3

With this, you're telling the compiler that you can't implicitly convert a Line to an Object:

class Line : protected Object {
};

But it seems to me that you want to do this, and also that you should do this. So make the inheritance public. This is a design question.

Don't make the inheritance protected just to keep methods in the base class protected.

One other option is to implement the cast operator in Line:

class Line : protected Object 
{
public:
   operator Object&();
};

and call the function like so:

a.Add(Line());

instead of

a.Add(new Line());

You can't implicitly cast pointers in this situation. However I suggest changing the inheritance type.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

Only friends and subclasses of Line can perform this cast. You could do this:

class Line : protected Object {
    friend class Array;
};

class Array {
public:
    template<class T>
    void Add (T &obj) {
        add_impl(obj); // cast is accessible here, because Array is a friend 
                       // of Line
    }

private:
    void add_impl(Obj &obj);
};

You don't have to use a function-template there, but I assumed you have more classes that derive from Object in this way, so a template would be helpful there.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • I could extend `Array` like you advise but aren't there solutions more closely approximating my proposed ones? Ie the implicit cast operator would be perfect. – John Dec 19 '11 at 09:07
  • By making the inheritance protected you are explicitly forbidding an implicit cast. This is contradictory. – Björn Pollex Dec 19 '11 at 09:08