Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!uunet!mcsun!ukc!stl!concurrent!concurrent.co.uk!asc From: asc@concurrent.co.uk (Andy Chittenden) Newsgroups: comp.lang.c++ Subject: problem with virtual inheritence Message-ID: <952@sl10c.concurrent.co.uk> Date: 14 Dec 89 12:45:36 GMT Sender: info@concurrent.co.uk Reply-To: asc@concurrent.co.uk (Andy Chittenden) Organization: Concurrent Computer Corp (ESDG), Slough, U.K. Lines: 66 The attached code demonstrates a problem when using C++ v2 virtual inheritence. We have a Collection class that can hold pointers to instances of class Object (or derived from Object). In the example, I have declared two collections. One is a collection of Widgets and the other is a collection of OtherWidgets. I can use my collection of Widgets as a collection of Widgets. I can add Widgets to the collection and I can get Widgets out of it. However, I can only use my collection of OtherWidgets as a collection of Objects. I can add OtherWidgets to the collection but can only get Objects out of it as OtherWidget virtually inherits from Object even though I only add OtherWidgets to it. Thus if I use virtual inheritence, I must reimplement my collection to be a collection of OtherWidgets. I have thus lost a lot of my code reuse. Has anyone else discovered this problem and if so, have they found a way out of it? Rgds, Andy Chittenden Program follows: class Object { public: Object(); }; class Collection : public Object { public: Collection(); unsigned long add_member(const Object* new_member); // returns pos of newly added member Object* get_Nth(unsigned long position); }; class Widget : public Object { public: Widget(); }; class OtherWidget : public virtual Object { public: OtherWidget(); }; main() { Widget x_widget; Collection x_widget_collection; x_widget_collection.add_member(&x_widget); Widget* widget_ptr; widget_ptr = (Widget *) x_widget_collection.get_Nth(1); OtherWidget x_otherwidget; Collection x_other_widget_collection; x_other_widget_collection.add_member(&x_otherwidget); OtherWidget* other_widget_ptr; other_widget_ptr = (OtherWidget *) x_other_widget_collection.get_Nth(1); // does not compile } "coll.cxx", line 40: error: cast: Object* ->derived OtherWidget*; Object is virtual base 1 error