Sei sulla pagina 1di 25

Dynamic Memory Management & Static Class Members

Lecture No 7
Object Oriented Programming

COMSATS Institute of Information Technology

Dynamic Memory Allocation


Static memory - where
global and static variables live

Object Oriented Programming

In C and C++, three types of memory are used by programs:

Heap memory dynamically allocated at execution time

- "managed" memory accessed using pointers Stack memory - used by


automatic variables

Kinds of Program Data

Object Oriented Programming

STATIC DATA: Allocated at compiler time

DYNAMIC DATA: explicitly allocated and deallocated 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

Dynamic Memory Allocation Diagram


Object Oriented Programming

High-end

Run-time allocated memory

Stack

Heap static data Program code

Compile-time allocated memory

Low-end

5
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

Operator new Syntax


TypeName *typeNamePtr;

Object Oriented Programming

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

Operator new
2000

char*

ptr;

??? 5000
ptr

ptr = new char;


*ptr = B; cout << *ptr;
5000
B

NOTE: Dynamic data has no variable name

The NULL Pointer

Object Oriented Programming

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 programmers job to check for this.

while (ptr != NULL) { . . . // ok to use *ptr here }

Operator delete
delete typeNamePtr;
typeNamePtr;

Object Oriented Programming

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.
9

10

Operator delete
char*
char* ptr;

Object Oriented Programming

ptr;

2000 5000 ???


ptr

ptr = new char; ptr = new char; *ptr = B;


*ptr = B;

cout cout <<

<< *ptr; *ptr; ptr;

5000
NOTE: delete deallocates the memory pointed to by ptr B

delete delete ptr;

11

Operator delete
char* ptr;
2000 5000 ???

ptr = new char; *ptr = B; cout << *ptr; delete ptr;

ptr

5000
B NOTE: delete deallocates the memory pointed to by ptr

Example
char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, Bye ); ptr 3000

12
Object Oriented Programming

??? NULL 6000 ???

ptr* 0 + = u;

6000
B y e \0 u // deallocates the array pointed to by ptr // ptr itself is not deallocated // the value of ptr becomes undefined

delete [] ptr; ptr = NULL;

13
Object Oriented Programming

In particular,
new invokes constructor delete invokes the classs destructor

14
Object Oriented Programming

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.

15
Object Oriented Programming

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.

16
Object Oriented Programming

17

Static Class Data

Object Oriented Programming

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

18
Object Oriented Programming

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

19

Uses of Static Class Data

Object Oriented Programming

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

class Race { private: Total car = 2, Car No. 10 static int count; //only one data item for all objects Total car = 2, Car No. 11 int carNo; public: Total car = 3, Car No. 12 Race() //increments count when object created { count++; carNo=0; } main() void setCarNo(int no) { { carNo = no; } Race c1, c2; //create three objects void printData() //returns count { cout<<Total car = << count; c1.setCarNo(10); c2.setCarNo(11); cout<<,Car No. = <<carNo<<endl; } c1.printData(); }; c2.printData(); int Race::count = 0; Race c3; c3.setCarNo(12); c3.printData(); main() } { Race c1, c2, c3; //create three objects c1.setCarNo(10); c2.setCarNo(11); c3.setCarNo(12); c1.printData(); Total car = 3, Car No. 10 c2.printData(); Total car = 3, Car No. 11 c3.printData(); } Total car = 3, Car No. 12

Object Oriented Programming

Example

20

21
Object Oriented Programming

Static vs. automatic member variable

Separate Declaration and Definition


Object Oriented Programming

22

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 variables 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

23

const Member Functions


class aClass { private: int alpha; public: void nonFunc() //non-const member function { alpha = 99; } //OK void conFunc() const //const member function { alpha = 99; } //ERROR: cant modify a member };

Object Oriented Programming

The non-const function nonFunc() can modify member data alpha, but the constant function conFunc() cant. 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 dont need to modify any data.

24
Object Oriented Programming

A Distance Example with const function

25
class Distance //English Distance class { private: int feet; float inches; public: //2-arg constructor Distance(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 const cout << football = ; football.showdist(); //OK }

const Objects
Object Oriented Programming

When an object is declared as const, it cant be modified

Potrebbero piacerti anche