Problem initializing object

Started by
1 comment, last by Naked Shooter 11 years, 7 months ago
Hi! I have an abstract GameOS object, and a windows implementation in WindowsOS.


class GameOS
{
private:
bool fullScreen;
public:
virtual void showWindow() = 0;
virtual void resize(U32 width, U32 height) = 0;
virtual void initialize() = 0;
virtual void processOSMessages()=0;
virtual void shutdown()=0;
virtual void setFullScreen(bool value) = 0;
};


I also have a platform detection class, where I try to allocate an OS object. For each platform, the platform detection class would use different cpp files. I was playing around with a custom stack allocator, trying to allocate the OS from a big stack that's passed in:


class PlatformDetection
{
private:

public:
PlatformDetection();
~PlatformDetection(void);


static GameOS* initAndReturnOS(StackAllocator& subsystemStack);
};


The windows implementation of the the initAndReturn function looks like this:


GameOS* PlatformDetection::initAndReturnOS(StackAllocator& subsystemStack)
{
WindowsOS* ret = (WindowsOS*)subsystemStack.allocateAligned(sizeof(WindowsOS), __alignof(WindowsOS));
memset(ret, 0, sizeof(WindowsOS));
ret->initialize();
return (GameOS*)ret;
}


The program crashes on ret->initialize(). The thing is, when I comment out "virtual void initialize() = 0;" in GameOS.h, it behaves normally, so it looks like it's trying to call an undefined function of GameOS rather than WindowsOS's function, even though the point is of type WindowsOS*...

Does anyone know why this is?
Advertisement
When you call memset(ret,0,sizeof(WindowsOS)); you might be trashing the vtable. If initialize is not a virtual function, then ret->initialize() doesn't need the vtable to be called, so it doesn't crash. I am curious as to why you used memset to clear that object.

When you call memset(ret,0,sizeof(WindowsOS)); you might be trashing the vtable. If initialize is not a virtual function, then ret->initialize() doesn't need the vtable to be called, so it doesn't crash. I am curious as to why you used memset to clear that object.


The memset was basically there for no reason, I thought it might help but it didn't..

The solution was to use a 'placement new' like this:


WindowsOS* ret = (WindowsOS*)subsystemStack.allocateAligned(sizeof(WindowsOS), __alignof(WindowsOS));
ret = new (ret) WindowsOS;


This way, we can properly construct an object wile using a pre-allocated chunk of memory to store it.

This topic is closed to new replies.

Advertisement