Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.

Slides:



Advertisements
Similar presentations
CSC 270 – Survey of Programming Languages C Lecture 6 – Pointers and Dynamic Arrays Modified from Dr. Siegfried.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Classes: A Deeper Look Systems Programming.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
1 CSC241: Object Oriented Programming Lecture No 13.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Learners Support Publications Classes and Objects.
1 CSC241: Object Oriented Programming Lecture No 06.
1 CSC241: Object Oriented Programming Lecture No 22.
C++ Memory Overview 4 major memory segments Key differences from Java
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 13: Pointers You are not responsible for virtual functions (starting on.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
CPSC 252 Dynamic Memory Allocation Page 1 Dynamic memory allocation Our first IntVector class has some serious limitations the capacity is fixed at MAX_SIZE.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Object-Oriented Programming in C++
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
Pointers and Dynamic Memory Allocation. Declaring a pointer.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
1 CSC241: Object Oriented Programming Lecture No 02.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1 CSC241: Object Oriented Programming Lecture No 05.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
1 CSC241: Object Oriented Programming Lecture No 03.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Object Oriented Programming COP3330 / CGS5409.  Aggregation / Composition  Dynamic Memory Allocation.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
CSC Pointers Powerful feature of the C++ language One of the most difficult to master Essential for construction of interesting data structures.
Memory Management.
CSC241: Object Oriented Programming
CSC241: Object Oriented Programming
CSC113: Computer Programming (Theory = 03, Lab = 01)
Pointers Revisited What is variable address, name, value?
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Dynamically Allocated Memory
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
FUNCTIONS& FUNCTIONS OVERLOADING
Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Classes and Objects.
Object Oriented Programming Using C++
Dynamic Memory.
C Programming Lecture-8 Pointers and Memory Management
C++ Plus Data Structures
Pointers, Dynamic Data, and Reference Types
Objects as Function Arguments
Presentation transcript:

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 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 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 ??? ptr 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 ‘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 ‘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’ ptr 3000 ??? 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

Example class 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 objects c1.setCarNo(10); c2.setCarNo(11); c3.setCarNo(12); c1.printData(); c2.printData(); c3.printData(); } Total car = 3, Car No. 10 Total car = 3, Car No. 11 Total car = 3, Car No. 12 main() { Race c1, c2; //create three objects c1.setCarNo(10); c2.setCarNo(11); c1.printData(); c2.printData(); Race c3; c3.setCarNo(12); c3.printData(); } Total car = 2, Car No. 10 Total car = 2, Car No. 11 Total 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 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: 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 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 constructor Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() //user input; non-const func { cout > feet; cout > 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 } Object Oriented Programming 25