You are on page 1of 9

Dynamic Memory Allocation :

It required memory allocation during run time (execution time)

Two operators: 1. new 2. delete


new - used to create heap memory space for an object of a class
syntax :
1) For single variable
datatype pointer=new datatype;
Ex : int ptr=new int;
2) For array variable
datatype pointer=new datatype[no.of elements];
Ex : int ptr=new int[10];

delete operator :
To destroy the variable space which has been created by using the new
dynamically
syntax :
delete pointer; - single variable
ex : delete ptr;
delete []pointer; - for an array
delete []ptr;
Create a memory for 10 integers using NEW operator and
destroy using the delete operator.
#include<iostream.h>
void main()
{
int *ptr,i;
ptr=new int[5];
cout<<endl<<"Enter 5 numbers";
for(i=0;i<5;i++)
{
cin>>*(ptr+i);
}
for(i=0;i<5;i++)
{
cout<<*(ptr+i)<<endl;
}
delete []ptr;
}
Write a C++ program to creates cout<<endl<<"enter the data";
an object of class book and cin>>bno>>author>>bname;
}
destroy it void book::show()
#include<iostream.h>
{
class book
cout<<endl;
{
cout<<bno<<author<<bname;
private :
}
int bno;
void main()
char author[15],bname[20];
public : {
void get(); book b1,*b2;
void show(); b2=new book;
~book() b1.get();
{ b2->get();
cout<<"Destructor called"<<endl; b1.show();
} b2->show();
}; delete b2;
void book::get(){ }

-> Used to access the member of the class through pointer


variable
Class USING new Operator ~String()
#include<iostream.h> {
delete str;
#include<string.h>
}
int length; void display()
class String {
{ cout<<str;
private : cout<<"\n Destructor
char *str; called";
public : }
String(char *s) };
{ void main()
length=strlen(s); {
String s1="Lafore";
str=new char[length+1]; // +1 ->
s1.display();
'\0' cout<<length;
strcpy(str,s); }
}
OUTPUT Lafore
6
Destructor called
It is a special pointer that exists for
a class while a non-static Member
function is executing.
It is used to access the address of
the Class itself and may return data
items to the caller.
#include<iostream.h>
class rectangle void main()
{ {
private : rectangle r;
int length,breadth; r.set_data(10,20);
public : r.show();
void set_data(int,int); }
void show();
};
void rectangle::set_data(int l,int b)
{
this->length=l; 10 20
this->breadth=b; OUTPUT
}
void rectangle ::show()
{
cout<<this->length<<this->breadth ;
}
this pointer Example void main()
#include<iostream.h> {
#include<conio.h> ptr p;
class ptr clrscr();
{ p.b();
private: getch();
int a; }
public:
void b()
{
a=10;
cout<<"this-> a value is"<<this->a;
cout<<"\n (*this).a value is“ <<(*this).a;
}
};
this-> a value is 10
OUTPUT (*this).a value is
10

You might also like