C++ trick question

Associate
Joined
26 Jan 2006
Posts
1,502
Assuming all the classes exists and everything, whats the problem?

Code:
Box* CreateShape::createBox(int x, int y)
{
     Box b(x, y);
     return &b;
}

I have my solution, but is best to let you guys go unbiased at it first :)

Thanks.
 
Isn't this a obvouis thing or am I missing something? You allocated on the stack, once it goes out of scope that object won't exist. So that pointer is invaild.


Normally i minimise the use of raw pointers in C++ using stl colletions, smart pointers and references.
 
Last edited:
Well, this is an exercise :p

My unserstanding is that the memory on the stack is again "free" as soon as the call returns. Any further calls will overwrite the memory contents while the call environment is setup etc. and therefore the pointer will point to junk.
 
You're creating a local variable which will be free'd once it goes out of scope, ie. 'b' will no longer exist.

Hence the point of the 'new' operator.
 
Back
Top Bottom