TITLE: "Avoiding" downcasts in container classes using unions PROBLEM: lowry@watson.ibm.com (Andy Lowry) [...] The idea is that the repository can hold items of various classes, each in the guise of an Item. Any code that gets items out of the repository knows (some how, not important) what class it really belongs to, and wants to cast it to that class to get at its full functionality. Is there any good way to do that, when some of the items in the repository are of classes that are virtually derived from Item? RESPONSE: maxtal@extro.ucc.su.OZ.AU (John MAX Skaller), 30 Mar 93 [ ... ] you are missing that you need to redesign so you dont need to downcast. A union is better. [ ... ] class AnItem { enum {t1, t2, t3} type; union { Item *i; Derived1 *d1; Derived2 *d2; Derived3 *d3; }; } it; switch(it.type) { case t1: it.d1->.... case t2: it.d2->.... case t3: it.d3-> .... } [ An alternative to this is to put virtual methods in Item, as shown below virtual Derived1* d1() CONST { return NULL} virtual Derived2* d2() CONST { return NULL} virtual Derived3* d3() CONST { return NULL} and have the derived classes override their particular method to return "this". The drawback of this is that the base class is polluted with knowledge of derived and must be modified everytime a new derived class is added. -adc ]