New and Delete in C++
C++ supports dynamic allocation and deallocation of objects using the new and delete operators.
The memory for C++ program is divided into two parts:
1. The stack: All variables declared inside the function will take up memory
from the stack.
2. The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs.
new OPERATOR :
You can allocate memory at run time within the heap for the variable of a given type using special operator in C++ which returns the address of the space allocated. This operator is called new operator.Syntax:
//Syntax for Primitive type *var = new type; //Syntax for Dynamic Array type *array_name = new type[size]; //Syntax for Object ClassName *ob = new Constructor;
delete OPERATOR :
If you are not in need of dynamically allocated memory anymore, you can use delete operator,which de-allocate memory previously allocated by new operator.Syntax:
delete ob_ref;
Code Example
#include<iostream> using namespace std; class Demo { public: void getName( ) { cout<<"Bjarne Stroustrup"<< endl; } }; int main() { Demo *ob = new Demo(); //use -> operator to access members ob->getName( ); delete ob; return 0; }
Next topic is Operator Overloading
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at info@prowessapps.in
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at info@prowessapps.in