Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!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: <6590168@hplsla.HP.COM> Date: 23 Jun 89 19:20:40 GMT References: <4413@druco.ATT.COM> Organization: HP Lake Stevens, WA Lines: 63 // (I'd much rather change just the virtual type field, // but I don't know how.) I think I'd discourage such an approach. Many C++ compilers optimize away some of the virtual function dispatch garbage if they unambigously "know" the type of an object at compile time. If you play dirty tricks to change the virtual table pointer, then virtual functions that get called from this object in the future, using the full dispatch protocol, will think your new object is indeed the new type, whereas virtual functions that the compiler determines [based on an unambiguous knowledge of type] don't need the full dispatch protocol will be of the old type. So you'd be making a scitzoid[sp] object. You might be able to do something like this: #include class base { int somecommonstuff; public: virtual char* classname(){return (char*)"base";} void printclass(){printf("object@%x is a %s\n",(unsigned)this,classname());} }; class X : public base { public: virtual char* classname(){return (char*)"X";} }; class Y : public base { public: virtual char* classname(){return (char*)"Y";} Y(X& x){this = (Y*)(&x);} }; main() { X x; x.printclass(); Y* yp = new Y(x); yp->printclass(); x.printclass(); // depends on the compiler } But this is still bad news for several reasons. 1) Assignment to this is a "feature" which is going obsolete and won't be supported on better optimizing compilers in the future. Perhaps something similar can be done using overloaded new, but I think it will still be a hack. 2) If you don't use the protocol, but rather use Y(X&) to intialize a static or a local, your program will probably [rightly] bomb, since a different object address has already been assigned by the compiler. 3) Again, the results of the final x.printclass() is going to depend on the compiler. My advice is to find a different approach to what you're trying to do. Is your idea based on experiences with other OOP languages? If so, please realize experience with other OOPLs is not necessarily an advantage when using C++.