Q: Common memory for new operator allocations I was asked an interview question: How can we allocate two objects of a class in different functions using the new operator such that they use the same memory space?
Can anyone explain how this can be achieved? Thanks.
EDIT: So the main question was how to create a class Memory_Alloc which should be used by all other classes to allocate memory for their objects. I thought about using Handles. Then he asked me the above question. 

A: The question is a little vague, but off the top of my head you could use:


*

*placement new -- use the new operator to initialize the same memory address

*overloaded new operator -- overload the new operator to return the same address

*delegation -- using pointer to implementation idiom, make two objects point to the same implementation object


A: With placement-new:
/* define class Foo */

void fun1(void * p) { ::new (p) Foo; }

void fun2(void * p) { ::new (p) Foo; }

int main()
{
    void * p = ::operator new(sizeof(Foo));

    fun1(p);

    p->~Foo();

    fun2(p);

    p->~Foo();

    ::operator delete(p);
}

Don't ever write code like that.

A: Impossible, because two objects always occupy different addresses, which is also the reason empty objects still have a size greater than zero. That said, for a trick question, you could create an object, destroy it again, and create another object at the same location.
Now, there is one question left: What exactly is a "memory space"? Did the interviewer mean address space perhaps?

A: 
How can we allocate two objects of a class in different functions using the new operator such that they use the same memory space?

Use placement new operator to do that.
Normally, the new operator has the responsibility of finding in the heap a block of memory
that is large enough to handle the amount of memory you request.The new operator
is called placement new, that allows you to specify the location to be used.
You could use this feature to set up your own memory-management procedures or to deal with hardware that is accessed via a particular address or to construct objects in a particular memory location.
struct AType
{
};

void func(AType*& p)
{
  p = new (p) AType;
}

int main()
{
  AType *p1 = new AType; 
  func(p1);
}

Also see placement new wiki link
