Sign in to follow this  
Naked Shooter

Problem initializing object

Recommended Posts

Hi! I have an abstract GameOS object, and a windows implementation in WindowsOS.

[CODE]
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;
};
[/CODE]

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:

[CODE]
class PlatformDetection
{
private:

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


static GameOS* initAndReturnOS(StackAllocator& subsystemStack);
};
[/CODE]

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

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

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
[quote name='RulerOfNothing' timestamp='1347777762' post='4980565']
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.
[/quote]

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:

[CODE]
WindowsOS* ret = (WindowsOS*)subsystemStack.allocateAligned(sizeof(WindowsOS), __alignof(WindowsOS));
ret = new (ret) WindowsOS;
[/CODE]

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this