[SDL] Problem with threads and virtual functions

Glenn Maynard g_sdl at zewt.org
Mon Nov 17 13:18:00 PST 2003


On Mon, Nov 17, 2003 at 02:29:26PM -0600, Tyler Montbriand wrote:
> Each thread is created via a static member of mtclass, with 'this' passed as 
> the object's pointer.  When the thread is allowed to run it calls the 
> pointer's virtual member.  No matter what I do it calls the BASE member, not 
> the overloaded one!

> mtclass::mtclass(int threads_in)
>   : l_mutex(NULL),l_cond(NULL),t_done(NULL),threads(0),running(0)
>   {
...
>     for(n=0; n<threads_in; n++)
>     {
>       SDL_Thread *t=SDL_CreateThread(threadroot,this);
>       if(t!=NULL) threads++;
>     }
>   }

You're creating the thread during the base class ctor.  In there, the object
is still the base class.  The base class ctor can not access the derived
class virtuals--they aren't there yet.

Try this:

struct parent {
	parent() { printf("parent ctor():\n"); func(); }
	virtual ~parent() {}
	virtual void func() { printf("A\n"); }
};

struct child: public parent {
	child() { printf("child ctor():\n"); func(); }
	virtual void func() { printf("B\n"); }
};

main() { child x;  }

# ./a.out
parent ctor():
A
child ctor():
B

For more information, I'd suggest:

  http://www.parashift.com/c++-faq-lite/

which explains this behavior and rationale.  (It's off-topic here; this
behavior isn't SDL's fault. :)

-- 
Glenn Maynard




More information about the SDL mailing list