Path: utzoo!telly!attcan!uunet!tut.cis.ohio-state.edu!UUNET.UU.NET!kewill!bryan From: kewill!bryan@UUNET.UU.NET (Bryan Boreham) Newsgroups: gnu.g++ Subject: Assignment to "this" causes vptr to be set. Message-ID: <8906171903.AA16063@kewill.uucp> Date: 17 Jun 89 19:03:47 GMT Sender: daemon@tut.cis.ohio-state.edu Distribution: gnu Organization: GNUs Not Usenet Lines: 68 // This is derived from a problem that I came across when porting ET++ // to g++ 1.35.1-. #include class Base { public: Base(); Base(int t) { } virtual void print() { printf("I'm a Base.\n"); } }; class Derived : public Base { public: Derived(int t) : (t) { } void print() { printf("I'm a Derived.\n"); } }; void MakeDer(Base **d) { *d = new Derived(3); } Base::Base() { Base* tmp_this; MakeDer(&tmp_this); tmp_this->print(); // I'm a Derived . this = tmp_this; // now it stuffs the vptr in this->print(); // I'm a Base. } int main() { Base* b = new Base; b->print(); // I'm a Base. delete b; return 1; } The idea is that Base should actually construct a Derived when called by new. ET++ uses a technique like this to make things like Font, Bitmap etc., window-system independant, but they used cfront, which apparently lets them call MakeDer(&this). I don't have access to a cfront compiler, so I can't check what this does. Anyway, g++ won't allow "&this", so I tried code like the above. Many wierd things happened, and I traced it to the fact that g++ stuffs in the vptr for Base after the first assignment to "this". If the assignment is in an if statement, the vptr gets set after the whole if. I am currently working round this by saving the value of the vptr as it comes from the desired class, and re-setting it after g++ has clobbered it, but I'd like to know what should really be happening. Perhaps there should be a way to take the address of "this"? Or a way to stop the vptr assignment? Maybe I missed the whole point. Bryan Boreham bryan@kewill.uucp or kewill!bryan@uunet.UU.NET Software Engineer {Atlantic Ocean} ... !mcvax!ukc!root44!kewill!bryan Kewill Systems PLC Work: (+44) 932 248 328 Walton-On-Thames Surrey KT12 2QS This is National No Quotes Week in Walton. England