- New and delete operator: used for memory allocation & deallocation in oop:
- C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory.
- C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.
- To allocate space dynamically, use the unary operator new
- The new operator signifies a request for memory allocation on the heap.
new
Syntax: datatype pointer_Variable = new datatype;
Here, the pointer-variable is the pointer of type data type.
Data type could be any built in data type including array or any user defined data type including class and structure.
Example: int *a= new float;
Uses: The main benefit of new over malloc() is that new doesn't just allocate memory, it constructs objects which is a prime concept of C++.
Uses: The main benefit of new over malloc() is that new doesn't just allocate memory, it constructs objects which is a prime concept of C++.
delete
- The delete operator is used to deallocate the memory created by new operator at runtime.
- Once the memory is no longer needed it should be free so that the memory becomes available again for other request of dynamic memory.
Syntax: delete pointer_variable;
Uses: Once heap memory is allocated to a variable or class object using the new keyword, we can deallocate that memory space using the delete keyword.
0 Comments