Introduction of Programming Lecture 28
Today’s Lecture How memory allocation is done in How memory allocation is done in C++ C++ How is it different from C style How is it different from C style Advantages of memory allocation in Advantages of memory allocation in C++ C++ Uses of memory allocation Uses of memory allocation – Classes – Objects
Pointers to a data structure
Pointers to a class
->
Memory Allocation
malloc ( ) ; calloc ( ) ; realloc ( ) ;
malloc ( 10 * ( sizeof ( int ) ) ) ;
free ( )
new
new int ;
int * iptr ; iptr = new int ; Example
new char ; new double ; Example
delete
int * iptr ; iptr = new int ; delete iptr ; Example
int * iptr ; iptr = new int [ 10 ] ; Example
new data_type [ Number_of_locations ] ; new double [ 10 ] ; Example
int *iptr ; iptr = new int [ 10 ] ; delete iptr ; Example
Date *dptr ; dptr is a pointer to an object of type date Example
dptr = new Date ;
main ( ) { Date mydate ; cout<< sizeof ( mydate ) ; } Example
int *iptr ; iptr = new int [ 10 ] ; Example
Date *dptr ; dptr = new Date [ 10 ] ; Example
Date date1, *dptr ; date1.setDate ( ) ; dptr = new Date ; dptr = new Date ; dptr ->setDate ( ); dptr.setDate ( ) ; Wrong Example
Protected
Destructor
Allocate enough space for Allocate enough space for the new data the new data Populate that space Populate that space Delete the previous space Delete the previous space Point the new space to the Point the new space to the pointer pointing to the pointer pointing to the original data original data
char *name =new char [ string_length ]
delete [ ] name
delete [ ] pointer_name
main ( ) { Date mydate ( “ ” ) ; Date mydate ( “ ” ) ; mydate.display ( ) ; } Example
Messages
Method