C++ Dynamic Memory
The new and delete operators are used in Dynamic Memory allocation.
The new operator
The new operator is used to create a heap memory space for the class object.
- To find the storage for the object to be created.
- Initialize the object
- Return a pointer to object
Syntax:
pointer =new data_type;
Example:
#include <iostream>
using namespace std;
class book{
private:
int a=3;
public:
void showdata();
};
void book::showdata()
{
cout << "Square of " << a << " is "<< a*a;
}
int main () {
book *b1;
b1=new book;
b1->showdata();
return 0;
}
The delete operator
The delete operator is used to destroy the variable space which has been created by using the new operator dynamically.
Syntax:
delete pointer;
Example:
#include <iostream>
using namespace std;
int main () {
int *p,i;
p=new int[5];
cout << " Enter the integers " << endl;
for(i=0; i<5 ; i++)
{
cin >> p[i];
}
cout << "Print the integers " << endl;
for(i=0; i<5 ; i++)
{
cout << p[i] << " ";
}
delete []p;
return 0;
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.