You are on page 1of 10

Session Objectives

Discuss Dynamic memory management technique

Discuss New & Delete Operator Explain Class using NEW operator Explain this pointer

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 an object of class book and destroy it

#include<iostream.h> class book { private : int bno; char author[15],bname[20]; public : void get(); void show(); ~book() { cout<<"Destructor called"<<endl; } }; void book::get(){

cout<<endl<<"enter the data"; cin>>bno>>author>>bname; } void book::show() { cout<<endl; cout<<bno<<author<<bname; } void main() { book b1,*b2; b2=new book; b1.get(); b2->get();; b2->show(); delete b2;

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

Class USING new Operator

#include<iostream.h> #include<string.h> int length; class String { private : char *str; public : String(char *s) { length=strlen(s); str=new char[length+1]; // +1 -> '\0' strcpy(str,s); }

~String() { delete str; } void display() { cout<<str; cout<<"\n Destructor called"; } }; void main() { String s1="Lafore"; s1.display(); cout<<length; }


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 :; void set_data(int,int); } void show(); }; void rectangle::set_data(int l,int b) { 10 this->length=l; OUTPUT this->breadth=b; } void rectangle ::show() { cout<<this->length<<this->breadth ; }


this pointer Example

#include<iostream.h> #include<conio.h> class ptr { private: int a; public: void b() { a=10; cout<<"this-> a value is"<<this->a; cout<<"\n (*this).a value is <<(*this).a; } };

void main() { ptr p; clrscr(); p.b(); getch(); }

this-> a value is 10 (*this).a value is 10