Question:
Is there a way to call a constructor on memory returned from malloc(...) in C++?
Example:
class CA
{
public:
CA() {};
virtual void foo() { printf( "CA\n" ); };
};
class CB : public CA
{
public:
CB() {};
virtual void foo() { printf( "CB\n" ); };
};
And in the code...
CB *p_cb = (CB*)malloc(sizeof(CB));
// Initialize?
p_cb->foo();
Explanation:
Okay, so without some type of initialization, the above program dies a horrible death because it won't initialize the vtables. Now, I know I could just use new which does this, but I'm now curious on "what if" this wasn't an option.
This came up between me and a friend discussing mem pools, so anyway, silly example...
So, say I want to extend stack memory, so I make a memstack class and in the init I just malloc a chunk of continuous memory. Awesome, I have memory. So it has an offset from the beginning. I have a method "alloc(size_t size)" that will save the current offset, move it by size, and then return the old offset.
Now I have a chunk of memory that needs to be initialized... and I have these awesome constructors already, but no idea how to call them on that returned memory.
*p_cb = CB() does indeed call the constructor, but doesn't set the vtable...
Anyway, sorry if this is stupidly simple... Been playing around with it for an hour and MSDN and google are no help... thought I'd post it here before bed and see if I got an answer by mornin' by the resident guru's.
Thanks!
PS: Saw something on a site that said you could "suppress" the constructor being called by new... they said nothing more, wish they did... it seems to be the other side of the same coin...