• Advertisement
Sign in to follow this  

Problem initializing object

This topic is 2046 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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. Edited by Naked Shooter

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement