The simple answer is yes.
You have a memory leak however. You are allocating the object
o
, but not releasing its memory.
int main()
{
x o = new x();
getch();
delete o; return 0;
}
Now to answer the question in the topic.
new
/
delete
has many uses.
Firstly dynamic memory allocation. All of this is exactly the same as the
malloc
/
free
functions:
When dealing with dynamic size data (for example the contents of a file) it is not practical to use the stack, because you have no idea how big the file will be.
char file_buffer[1024];
int file_size = ; char *file_buffer = new char[file_size];
Typically when dealing with large amounts of memory you would use the heap, with
new
/
delete
or
malloc
/
free
. Your program has limited (although usually quite large) stack space. If you run out of stack your program will crash abruptly. At least if you run out of heap
malloc
will return null or
new
will thrown an exception, both of which you can handle as needed.
Now for the differences in
new
/
delete
and
malloc
/
free
.
new
calls the constructor,
delete
calls the destructor. malloc/free don't.
new
automatically gets the correct data size when allocating.
int *numbers = (int *)malloc(10 * sizeof(int));
int *numbers = new int[10];
When allocating an array with new, you must use
delete[]
int *numbers = new int[10];
delete[] numbers;