Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!tut.cis.ohio-state.edu!ucbvax!hplabs!hp-pcd!hplsla!jima From: jima@hplsla.HP.COM (Jim Adcock) Newsgroups: comp.lang.c++ Subject: Re: Question: Object transformations in C++ Message-ID: <6590173@hplsla.HP.COM> Date: 28 Jun 89 17:48:17 GMT References: <4413@druco.ATT.COM> Organization: HP Lake Stevens, WA Lines: 47 > / hplsla:comp.lang.c++ / john@hhb.UUCP (John Sissler) / 7:21 am Jun 24, 1989 / > > How can an instantiation of one derived class transform into a > > different derived class of the same base class? The derived classes > > have different virtual functions but have no additional private data, > > so what I really would like to do is just change the "virtual" type field. > > Below is some code that I hope illustrates the problem. > > I have had the same desire to change the virtual table in order to > transform instances, and I suppose this is my opportunity to > come out of the closet. > > My scenario is essentially this: during initialization of a > performance-critical application, a graph of instances is created. > After the graph is complete, each node is given a chance to > optimize itself based on information which is available only > after the graph is complete. Each node is constrained to occupy > the same space. Due to performance and memory requirements, > indirection (i.e. instance handles / instance pointer table) is > not an alternative. Thus, one means by which the instance can > optimize itself is to modify its virtual table to acquire a set > of "fast" methods. > > A cfront-dependent method of achieving this is > to simply modify the vptr field, for example: > > void Derived::Transform(const AnotherDerived& newInstance) { > _vptr = newInstance._vptr; > } > > Admittedly, I have only experimented with this technique, and > I doubt whether I'll actually use it in production code unless > it gets language support (which I doubt it will or should). The example I gave before using initializers to change a vtable pointer of an existing object will work in this example -- though you'd still probably want to do it by overloading new vs the "this assignment" I used. If you only change an object derived from some base class with virtual functions, only use those virtual functions with the changed object, the changed object being one of several different derived classes, and only refer to the object using base class pointers, then this trick should be pretty safe. The point is that you must not allow a compiler to "figure out" an object's "true type" at compile time -- since you've changed the run-time portion of an object's type -- the vtable pointer -- behind the compiler's back. These techniques still have to be considered "dirty pool" that may get you in trouble in the future as compilers and the language progress.