Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!uflorida!haven!purdue!bu-cs!att!cbnews!trm From: trm@cbnews.ATT.COM (Tom R. Mueller) Newsgroups: comp.lang.c++ Subject: Re: Question: Object transformations in C++ Message-ID: <7748@cbnews.ATT.COM> Date: 26 Jun 89 14:29:50 GMT References: <4413@druco.ATT.COM> Reply-To: trm@cbnews.ATT.COM (Tom R. Mueller) Distribution: comp Organization: AT&T Bell Laboratories Lines: 52 Here's a portable way to change the vtbl entry. This example transforms an object from a base class to a derived class. It uses forwarding functions in the base class to redirect calls through the vtbl. Note that if you're calling functions in a derived class using d.func(), the vtbl isn't referenced so changing it won't help. #include class Base { public: Base() { cout << "Constructing Base.\n"; } void makeMeADerived(); virtual void f() { cout << "Called Base::f()\n"; this->f(); } void *operator new(long) { return ::new Base; }; void *operator new(long, void *where) { return where; } void operator delete(void *) { } }; class Derived : public Base { public: Derived() { cout << "Constructing Derived.\n"; } void f() { cout << "Called Derived::f()\n"; } }; void Base::makeMeADerived() { Derived *d = new(this) Derived; } main() { Base b; b.makeMeADerived(); b.f(); // Calls Derived::f (indirectly via Base) (&b)->f(); // Calls Derived::f (directly via vtbl) } -- - Tom Mueller AT&T Bell Laboratories (CB 0D109) (614) 860-5287 6200 East Broad Street ...att!cblpn!trm Columbus, OH 43213