Question

For wxWidgets, why do you need to say:

MyFrame *frame = new MyFrame

instead of:

MyFrame frame;

What's the difference between the two? The second one is nicer to read and easier to use but all examples use the first so I wondered what the reason is.

Just to clarify, I know the second version doesn't work, but I'm wondering if there's a specific design decision which leads to having to use the first form instead of the second. TIA.

Was it helpful?

Solution

The first allocates a new MyFrame instance on the heap, and returns a pointer to it. The second creates a new MyFrame instance on the stack directly.

The reason you need to use the first syntax is that you will add this frame (UI element) into another UI element, such as a window. The window will take the pointer to a frame, and add it as a child.

If you use the second syntax, you'd have to pass a pointer to your stack object (&frame), which would compile, but then as soon as your method returned, frame's destructor would get called since frame would go out of scope. This would "break" the reference inside of your window.

OTHER TIPS

If you use 'new' you are allocating the frame on the heap. Otherwise it's allocated on the stack, and will be deleted when the stack frame ends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top