🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Bryan Boreham Sat, 17 Jun 1989 19:03
Assignment to "this" causes vptr to be set.
#4
Author: Bryan Boreham
Date: Sat, 17 Jun 1989 19:03
68 lines
2307 bytes
// This is derived from a problem that I came across when porting ET++
// to g++ 1.35.1-.

#include <stdio.h>

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
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads