[c++] When to use "new" and when not to, in C++?

Possible Duplicate:
When should I use the new keyword in C++?

When should I use the "new" operator in C++? I'm coming from C#/Java background and instantiating objects is confusing for me.

If I've created a simple class called "Point", when I create a point should I:

Point p1 = Point(0,0);

or

Point* p1 = new Point(0, 0);

Can someone clarify for me when to use the new operator and when not to?

Duplicate of:

When should I use the new keyword in C++?

Related:

About constructors/destructors and new/delete operators in C++ for custom objects

Proper stack and heap usage in C++?

This question is related to c++ new-operator

The answer is


New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

Take a look at this question and this question for some good answers on C++ object instantiation.

This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.

void SomeFunc()
{
    Point p1 = Point(0,0);
} // p1 is automatically freed

void SomeFunc2()
{
    Point *p1 = new Point(0,0);
    delete p1; // p1 is leaked unless it gets deleted
}

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.