Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde!uunet!wuarchive!uwm.edu!ux1.cso.uiuc.edu!ux1.cso.uiuc.edu!m.cs.uiuc.edu!madany From: madany@m.cs.uiuc.edu Newsgroups: comp.lang.c++ Subject: Re: Chameleon objects (calling virtual Message-ID: <4800075@m.cs.uiuc.edu> Date: 6 Dec 89 01:38:52 GMT References: <11266@csli.Stanford.EDU> Lines: 47 Nf-ID: #R:csli.Stanford.EDU:11266:m.cs.uiuc.edu:4800075:000:1990 Nf-From: m.cs.uiuc.edu!madany Dec 5 08:59:00 1989 /* Written 3:07 pm Dec 4, 1989 by keith@csli.Stanford.EDU in m.cs.uiuc.edu:comp.lang.c++ */ /* ---------- "Chameleon objects (calling virtual" ---------- */ >> (The fix, of course, is to call the Instantiate function from each >> derived constructor, instead of the base class. The problem is that >> it is then not possible to derive further sub classes of a derived type, >> as the intermediate class will create unwanted instantiations of >> themselves as their intermediate constructor functions are called.) Not quite true. You can define two constructors for each class, with different numbers of parameters. For example: SubClass::SubClass( parameters ) : Class( parameters, 0 ) { Instantiate(context); ... } and SubClass::SubClass( parameters, int ) : Class( parameters, 0 ) { ... } Then the compiler could distinguish between the two constructors. For each class, use the constructor without the extra int when creating objects of that class, and use the constructor with the int when calling up the constructor chain. Now you have a way to avoid calling some function twice, you can insert code that should only be called once for an object in the constructor used for object creation, and you can subclass to your hearts content. >> Is this reasonable semantics for virtual function calling? I know that it >> is somewhat bogus to do anything with the derived object before its >> constructor has been called, but I do not find anything which says >> that it is illegal. In this case, my virtual function calls are not >> actually operating on the derived object, but are rather creating a >> parallel structure in a different context. This semantics for calling virtual functions in constructors seems reasonable to me, though it can be frustrating in cases similar to the one you described. It makes sense that an object belongs to the class of a currently executing constructor or destructor and not to any subclass. -peter madany