View
29
Download
0
Category
Preview:
DESCRIPTION
hgshdghs
Citation preview
Dynamic Memory Management & Static Class Members
Lecture No 7Object Oriented Programming
COMSATS Institute of Information Technology
Dynamic Memory Allocation
• Static memory - where global and static variables live
• Heap memory - dynamically allocated at execution time- "managed" memory accessed using pointers
• Stack memory - used by
automatic variables
2
In C and C++, three types of memory are used by programs:
Object Oriented Programming
Kinds of Program Data
•STATIC DATA: Allocated at compiler time
•DYNAMIC DATA: explicitly allocated and de-allocated during program execution by C++ instructions written by programmer using operators new and delete
•AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function
3
Object Oriented Programming
Dynamic Memory Allocation Diagram
4
s ta tic da ta
S tack
H eap
Run-tim
e allo
cate
d
mem
ory
Com
pile
-time
allo
cate
d
mem
ory
P rog ramcode
H igh -end
Low -end
Object Oriented Programming
Dynamic Memory Allocation • In C, functions such as malloc() are used to
dynamically allocate memory from the Heap.• In C++, this is accomplished using the new
and delete operators• new is used to allocate memory during
execution time– returns a pointer to the address where the
object is to be stored– always returns a pointer to the type that
follows the new
5
Object Oriented Programming
Operator new Syntax
TypeName *typeNamePtr;
typeNamePtr = new TypeName;
If memory is available, in an area called the heap (or free store) new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated.
Otherwise, program terminates with error message.
The dynamically allocated object exists until the delete operator destroys it. 6
Object Oriented Programming
6
Operator new
char* ptr;
ptr = new char;
*ptr = ‘B’; cout << *ptr;
NOTE: Dynamic data has no variable name
7
2000
???
ptr
5000
5000
‘B’
The NULL Pointer
•There is a pointer constant called the “null pointer” denoted by NULL
•But NULL is not memory address 0.
•NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this.
while (ptr != NULL) { . . . // ok to use *ptr here }
8
Object Oriented Programming
Operator delete
• The object or array currently pointed to by Pointer is deallocated, and the value of Pointer is undefined. The memory is returned to the free store.
•Good idea to set the pointer to the released memory to NULL
• Square brackets are used with delete to deallocate a dynamically allocated array.
delete [ ] typeNamePtr;
delete typeNamePtr;
9
Object Oriented Programming
9
Operator delete
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
delete ptr;
10
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
delete ptr;
5000
5000
‘B’
2000
ptr
???
NOTE: delete deallocates the memory pointed to by ptr
Object Oriented Programming
11
Operator delete
char* ptr;
ptr = new char;
*ptr = ‘B’;
cout << *ptr;
delete ptr;
5000
5000
‘B’
2000
ptr
???
NOTE: delete deallocates the memory pointed to by ptr
Example 12
char *ptr ;
ptr = new char[ 5 ];
strcpy( ptr, “Bye” );
ptr[ 0 ] = ‘u’;
delete [] ptr;
ptr = NULL;
‘B’ ‘y’ ‘e’ ‘\0’‘u’
ptr3000
???
6000
6000???NULL
// deallocates the array pointed to by ptr// ptr itself is not deallocated// the value of ptr becomes undefined
Object Oriented Programming
•In particular,▫new invokes constructor▫delete invokes the class’s destructor
Object Oriented Programming
13
Classes, Objects, and Memory•Each object has its own separate data
items•All the objects in a class use the same
member functions•Member functions are created and placed
in memory only once, when they are defined in the class declaration.
•No need to duplicate all member functions in a class every time you create another object of that class, since functions for each object are identical.
Object Oriented Programming
14
•Data items will hold different values, so separate instance of each data item for each object.
•So, data placed in memory when each object is defined, so there is a separate set of data for each object.
Object Oriented Programming
15
Object Oriented Programming
16
Static Class Data•If a data item in a class is declared as
static, only one such item is created for the entire class, no matter how many objects there are
•A member variable defined as static has characteristics similar to a normal static variable: It is visible only within the class, but its lifetime is the entire program.
•It continues to exist even if there are no objects of the class
Object Oriented Programming
17
Cont.
•A static data item is useful when all objects of the same class must share a common item of information
•A normal static variable is used to retain information between calls to a function, static class member data is used to share information among the objects of a class
Object Oriented Programming
18
Uses of Static Class Data•Suppose an object needed to know how
many other objects of its class were in the program
•In a road-racing game, for example, a race car might want to know how many other cars are still in the race
•In this case a static variable count could be included as a member of the class
•All the objects would have access to this variable
Object Oriented Programming
19
Exampleclass Race{ private: static int count; //only one data item for all objects int carNo; public: Race() //increments count when object created { count++; carNo=0; } void setCarNo(int no) { carNo = no; } void printData() //returns count { cout<<“Total car = ”<< count; cout<<“,Car No. = ”<<carNo<<endl; }};int Race::count = 0; main(){
Race c1, c2, c3; //create three objectsc1.setCarNo(10); c2.setCarNo(11); c3.setCarNo(12); c1.printData();c2.printData();c3.printData();
}
Total car = 3, Car No. 10Total car = 3, Car No. 11Total car = 3, Car No. 12
main(){
Race c1, c2; //create three objectsc1.setCarNo(10); c2.setCarNo(11); c1.printData();c2.printData();Race c3; c3.setCarNo(12); c3.printData();
}
Total car = 2, Car No. 10Total car = 2, Car No. 11Total car = 3, Car No. 12
Object Oriented Programming
20
Static vs. automatic member variable
Object Oriented Programming
21
Separate Declaration and Definition
• Ordinary variables are usually declared (the compiler is told about their name and type) and defined (the compiler sets aside memory to hold the variable) in the same statement
• Static member data requires two separate statements– The variable’s declaration appears in the class
definition, – but the variable is actually defined outside the
class• Putting the definition of static member data
outside the class also serves to emphasize that the memory space for such data is allocated only once
Object Oriented Programming
22
const Member Functionsclass aClass{private: int alpha;public:void nonFunc() //non-const member function{ alpha = 99; } //OKvoid conFunc() const //const member function{ alpha = 99; } //ERROR: can’t modify a member};• The non-const function nonFunc() can modify member data alpha, but the
constant function conFunc() can’t. If it tries to, a compiler error results.
• Member functions that do nothing but acquire data from an object are obvious candidates for being made const, because they don’t need to modify any data.
Object Oriented Programming
23
A Distance Example
with const function
Object Oriented Programming
24
const Objects
• When an object is declared as const, it can’t be modified
class Distance //English Distance class{private:int feet;float inches;public: //2-arg constructorDistance(int ft, float in) : feet(ft), inches(in){ }void getdist() //user input; non-const func{cout << “\nEnter feet: “; cin >> feet;cout << “Enter inches: “; cin >> inches;}void showdist() const //display distance; const func{ cout << feet << “:” << inches; }};main(){const Distance football(300, 0);// football.getdist(); //ERROR: getdist() not constcout << “football = “;football.showdist(); //OK}
Object Oriented Programming
25
Recommended