310 likes | 412 Views
This lecture covers pointers, references, memory allocation, dynamic memory allocation, copy constructor, and assignment operators. Get insights into deep and shallow copies, pointers to objects, and the rules for dynamic memory allocation in programming.
E N D
Introduction to Programming Lecture 39
Review • Pointers • References • Memory Allocation
Pointers A pointer is a special type of variable that contain a memory address
Void Pointer • Pointer to an Integer • Pointer to a Character • Pointer to a Float • Pointer to Objects
Native Operator • new • delete
Dynamic Memory Allocation int *p ; p = new int ; delete p ;
Dynamic Memory Allocation int *p ; p = new int [ 10 ] ; delete [ ] p ;
Example class Matrix { private : int * m ; int row , col ; public : Matrix ( int rows , int cols ) { m = new int [ rows * cols ] ; } } ;
int i = 0 ; //Initialization int i ; i = 0 ; //Assignment
Matrix m1 , m2 ; …… m2 = m1 ; //Assignment Statement
Pointing to the same region in memory int *m of m1 0xefffdad0 mx int *m of m2 0xefffdad0
Pointing to the same region in memory int *m of m1 0xefffdad0 mx int *m of m2 0xefffdad0
Deep Copy Shallow Copy
Example class String { char * c ; public : void copy ( char * s ) ; String ( char * data ) ; void print ( ) ; // etc. } ;
Example String s1 ( “test1” ) ; String s2 = s1 ; s1.copy ( “this is a test” ) ; s2.print ( ) ;
int i ; i = 10 ; i = i ;
Matrix m2 ( m1 ) ; Matrix m2 = m1 ;
Rules For dynamic memory allocation • Define copy constructor • Write assignment operator • Provide destructor
What have we covered today • Review of pointers • Dynamic memory allocation • new • Delete • For memory allocation in classes we must provide • Constructor • Copy constructor • Assignment operator • destructor