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: <6590179@hplsla.HP.COM> Date: 30 Jun 89 19:30:01 GMT References: <4413@druco.ATT.COM> Organization: HP Lake Stevens, WA Lines: 50 //Here's a little cleaner approach based on a combo of previous listings that //might be reasonable. The idea is to match the compile-time type of the //object to the run-time type of the object, using references. So now you //have a new object "d" that occupies the space previously held by "b", //the vtable pointer of "b" having been overwritten as a result of //Derived::new(long, Base&). Presumably values of instance variables of //b will be retained for d to use. Of course if one makes the mistake of //accessing b after it has been cannibalized by d, you'd still be in deep //xxxx trouble. //whether this is actually going to be fast enough to meet your goals depends //on your goals, and your compiler. #include class Derived; class Base { public: Base() { cout << "Constructing Base.\n"; } virtual void f() { cout << "Called Base::f()\n"; } }; class Derived : public Base { public: Derived() { cout << "Constructing Derived.\n"; } void f() { cout << "Called Derived::f()\n"; } void * operator new(long) { return ::new Derived; } void * operator new(long, Base& b) { return &b; } void operator delete(void *) { } }; main() { Base b; b.f(); cout << "\n"; Derived& d = *(new(b) Derived); cout << "\n"; d.f(); // How this gets called depends on the compiler? ((Base *)(&d))->f(); // whereas this get called via vtable? }