Final Exam Tues 31610 2 3 50 Same

  • Slides: 70
Download presentation
Final Exam Tues 3/16/10 (2 -3: 50) (Same classroom) Old Textbook - Chapters 11

Final Exam Tues 3/16/10 (2 -3: 50) (Same classroom) Old Textbook - Chapters 11 -16, 18 Focus is on 15, 16 and 18 Multiple choice, True/False and some minimal programming will be required 1

Topics Covered • • List Structures (Arrays & Linked List) C++ Classes Inheritance Object-Oriented

Topics Covered • • List Structures (Arrays & Linked List) C++ Classes Inheritance Object-Oriented Programming Pointers Dynamic Memory Recursion 2

Array-Based List 3

Array-Based List 3

Linked List ADT 4

Linked List ADT 4

Array List vs. Linked List ADT Array List • Pre-allocation Required • Waste-full if

Array List vs. Linked List ADT Array List • Pre-allocation Required • Waste-full if you allocate too much • Fatal if you allocate too little • Data has to be shifted when an item is inserted or deleted at specified position Linked List • Truly dynamic, memory is allocated as needed • No shifting when an item is inserted, deleted 5

For the Final Exam You will NOT be asked to write a Linked List.

For the Final Exam You will NOT be asked to write a Linked List. You don’t have to create an array either. Questions related to Link List and Arrays are concept based, (no code writing). 6

Structured Data Type Definition: A structured data type is a type in which each

Structured Data Type Definition: A structured data type is a type in which each value is a collection of component items. The entire collection has a single name each component can be accessed individually Know what is meant by a structured data type. You do not need to create a struct or use on the final exam. 7

Accessing struct Members Dot ( period ) is the member selection operator. After the

Accessing struct Members Dot ( period ) is the member selection operator. After the struct type declaration, the various members can be used in your program only when they are preceded by a struct variable name and a dot. EXAMPLES this. Animal. weight another. Animal. country 8

Abstraction is the separation of the essential qualities of an object from the details

Abstraction is the separation of the essential qualities of an object from the details of how it works or is composed It focuses on what, not how It is necessary for managing large, complex software projects 9

Abstract Data Type (ADT) Is a programmer-defined type with a set of values and

Abstract Data Type (ADT) Is a programmer-defined type with a set of values and allowable operations for the type. Some ways to define a new C++ type are: using struct using class 10

ADT Specification Example TYPE Time. Type DOMAIN Each Time. Type value is a time

ADT Specification Example TYPE Time. Type DOMAIN Each Time. Type value is a time in hours, minutes, and seconds. OPERATIONS Set the time Print the time Increment by one second Compare 2 times for equality Determine if one time is “less than” another 11

ADT Implementation means Choosing a specific data representation for the abstract data using data

ADT Implementation means Choosing a specific data representation for the abstract data using data types that already exist (built-in or programmer-defined) Called “Data Members” Writing functions (member functions) for each allowable operation 12

Information Hiding Class implementation details are hidden from the client’s view. This is called

Information Hiding Class implementation details are hidden from the client’s view. This is called information hiding. Public functions of a class provide the interface between the client code and the class objects. client code specification abs trac bar tion rier implementation 13

Benefits of information hiding Data and details can be concealed from the client of

Benefits of information hiding Data and details can be concealed from the client of the abstraction. Code can be changed without affecting the client because the specification and interface are unchanged. 14

class Time. Type Specification // Specification File ( timetype. h ) class Time. Type

class Time. Type Specification // Specification File ( timetype. h ) class Time. Type { // declares a class data type // does not allocate memory public : // 5 public function members void bool Set ( int hours , int mins , int secs ) ; Increment ( ) ; Write ( ) const ; Equal ( Time. Type other. Time ) const ; Less. Than ( Time. Type other. Time ) const ; private : }; int int // 3 private data members hrs ; mins ; secs ; 15

Use of C++ data Type class Facilitates re-use of C++ code for an ADT

Use of C++ data Type class Facilitates re-use of C++ code for an ADT Software that uses the class is called a client Variables of the class type are called class objects or class instances Client code uses public member functions to handle its class objects 16

Using class A class is a programmer-defined type whose components (called class members) can

Using class A class is a programmer-defined type whose components (called class members) can be variables or functions. Class members are private by default. Compiler does not permit client code to access private class members. Class members declared public form the interface between the client and the class. In most classes, the private members contain data, and the public members are functions to manipulate that data. 17

Member functions categorized by task CONSTRUCTOR -- a member function that actually creates a

Member functions categorized by task CONSTRUCTOR -- a member function that actually creates a new instance and initialized some or all of its data members ACCESS FUNCTION or OBSERVER -- a member function that can inspect (use but not modify) the data members of a class without changing their values. Such a function is declared with const following the parameter list in both the specification and the implementation files. 18

Client Code Using Time. Type #include “timetype. h” using namespace std ; int main

Client Code Using Time. Type #include “timetype. h” using namespace std ; int main ( ) { Time. Type bool current. Time ; end. Time ; done = false ; // includes specification of the class // declares 2 objects of Time. Type current. Time. Set ( 5, 30, 0 ) ; end. Time. Set ( 18, 30, 0 ) ; while ( ! done ) {. . . }; current. Time. Increment ( ) ; if ( current. Time. Equal ( end. Time ) ) done = true ; } 19 19

class type Declaration The class declaration creates a data type and names the members

class type Declaration The class declaration creates a data type and names the members of the class. It does not allocate memory for any variables of that type! Client code still needs to declare class variables. 20

C++ Data Type class represents an ADT 2 kinds of class members: data members

C++ Data Type class represents an ADT 2 kinds of class members: data members and function members Class members are private by default Data members are generally private Function members are generally declared public Private class members can be accessed only by the class member functions (and friend functions), not by client code. 21

Aggregate class Operations Built-in operations valid on class objects are: Member selection using dot

Aggregate class Operations Built-in operations valid on class objects are: Member selection using dot (. ) operator , Assignment to another class variable using ( = ), Pass to a function as argument (by value or by reference), Return as value of a function Other operations can be defined as class member functions 22

2 separate files Generally Used for class Type // Specification File ( timetype. h

2 separate files Generally Used for class Type // Specification File ( timetype. h ) // Specifies the data and function members. class Time. Type { public: . . . private: . . . }; // Implementation File ( timetype. cpp ) // Implements the Time. Type member functions. . 23

Implementation File for Time. Type // Implementation File ( timetype. cpp ) // Implements

Implementation File for Time. Type // Implementation File ( timetype. cpp ) // Implements the Time. Type member functions. #include “ timetype. h” // also must appear in client code #include <iostream>. . . bool Time. Type : : Equal (Time. Type other. Time ) const // // Function value == true, if this time equals other. Time == false , otherwise { return ( (hrs == other. Time. hrs) && (mins == other. Time. mins) && (secs == other. Time. secs) ) ; } . . . 24

Scope Resolution Operator ( : : ) C++ programs typically use several class types

Scope Resolution Operator ( : : ) C++ programs typically use several class types Different classes can have member functions with the same identifier, like Write( ) Member selection operator is used to determine the class whose member function Write( ) is invoked current. Time. Write( ) ; number. Z. Write( ) ; // class Time. Type // class Complex. Number. Type In the implementation file, the scope resolution operator is used in the heading before the function member’s name to specify its class void Time. Type : : Write ( ) const { } . . . 25

Class Constructors A class constructor is a member function whose purpose is to initialize

Class Constructors A class constructor is a member function whose purpose is to initialize the private data members of a class object The name of a constructor is always the name of the class, and there is no return type for the constructor A class may have several constructors with different parameter lists. A constructor with no parameters is the default constructor A constructor is implicitly invoked when a class object is declared--if there are parameters, their values are listed in parentheses in the declaration 26

Specification of Time. Type Class Constructors class Time. Type // timetype. h { public

Specification of Time. Type Class Constructors class Time. Type // timetype. h { public : // 7 function members void Set ( int hours , int minutes , int seconds ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( Time. Type other. Time ) const ; bool Less. Than ( Time. Type other. Time ) const ; Time. Type ( int init. Hrs , int init. Mins , int init. Secs ) ; // constructor Time. Type ( ) ; private : int int }; // default constructor // 3 data members hrs ; mins ; secs ; 27 27

Implementation of Time. Type Default Constructor Time. Type : : Time. Type ( )

Implementation of Time. Type Default Constructor Time. Type : : Time. Type ( ) // Default Constructor // Postcondition: // hrs == 0 && mins == 0 && secs == 0 { hrs = 0 ; mins = 0 ; secs = 0 ; } 28

Implementation of Another Time. Type Class Constructor Time. Type : : Time. Type (

Implementation of Another Time. Type Class Constructor Time. Type : : Time. Type ( int init. Hrs, int init. Mins, int init. Secs ) // Constructor // Precondition: 0 <= init. Hrs <= 23 && 0 <= init. Mins <= 59 // 0 <= init. Secs <= 59 // Postcondition: // hrs == init. Hrs && mins == init. Mins && secs == init. Secs { hrs = init. Hrs ; mins = init. Mins ; secs = init. Secs ; } 29

Separate Compilation and Linking of Files specification file main program timetype. h client. cpp

Separate Compilation and Linking of Files specification file main program timetype. h client. cpp implementation file timetype. cpp #include “timetype. h” Compiler client. obj timetype. obj Linker client. exe 30

For the Final Exam Note: You will be asked to write a simple class,

For the Final Exam Note: You will be asked to write a simple class, without using dynamic memory. (no Copy Constructor or Destructor writing will be required. ) You should know what a copy constructor and a destructor is in concept. 31

Pointers • A pointer holds the memory address of another object. • Through the

Pointers • A pointer holds the memory address of another object. • Through the pointer we can indirectly manipulate the referenced object. Pointers are useful for • Creating linked data structures such as linked lists, • management of dynamically allocated objects, and • as a function parameter type for passing large objects such as arrays. 32

Pass-by-value sends a copy of the contents of the actual parameter CALLING BLOCK FUNCTION

Pass-by-value sends a copy of the contents of the actual parameter CALLING BLOCK FUNCTION CALLED SO, the actual parameter cannot be changed by the function. 33

Pass-by-reference sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED

Pass-by-reference sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED can change value of actual parameter 34

Obtaining Memory Addresses the address of a non-array variable can be obtained by using

Obtaining Memory Addresses the address of a non-array variable can be obtained by using the address-of operator & int float char x; number; ch; cout << “Address of x is “ << &x << endl; cout << “Address of number is “ << &number << endl; cout << “Address of ch is “ << &ch << endl; 35

What is a pointer variable? A pointer variable is a variable whose value is

What is a pointer variable? A pointer variable is a variable whose value is the address of a location in memory. to declare a pointer variable, you must specify the type of value that the pointer will point to, for example, int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char 36

Using a Pointer Variable 2000 int x; x = 12; 12 x int* ptr;

Using a Pointer Variable 2000 int x; x = 12; 12 x int* ptr; ptr = &x; 3000 2000 ptr NOTE: Because ptr holds the address of x, we say that ptr “points to” x 37

Unary operator * is the indirection (deference) operator 2000 int x; x = 12;

Unary operator * is the indirection (deference) operator 2000 int x; x = 12; 12 x int* ptr; ptr = &x; cout << *ptr; 3000 2000 ptr NOTE: The value pointed to by ptr is denoted by *ptr 38

Using the Dereference Operator 2000 int x; x = 12; 12 5 x int*

Using the Dereference Operator 2000 int x; x = 12; 12 5 x int* ptr; ptr = &x; 3000 2000 ptr *ptr = 5; // changes the value // at address ptr to 5 39

Another Example char ch = 4000 ch; ‘A’; char* q; q = &ch; A

Another Example char ch = 4000 ch; ‘A’; char* q; q = &ch; A Z ch 5000 6000 4000 *q = ‘Z’; char* p; p = q; q 4000 p // now p and q both point to ch 40

Operator new Syntax new Data. Type [Int. Expression] If memory is available, in an

Operator new Syntax new Data. Type [Int. Expression] 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. 41

3 Kinds of Program Data STATIC DATA: memory allocation exists throughout execution of program

3 Kinds of Program Data STATIC DATA: memory allocation exists throughout execution of program AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete 42

Dynamically Allocated Data char* ptr; ptr = new char; 2000 ptr *ptr = ‘B’;

Dynamically Allocated Data char* ptr; ptr = new char; 2000 ptr *ptr = ‘B’; cout << *ptr; ‘B’ NOTE: Dynamic data has no variable name 43

Dynamically Allocated Data char* ptr; ptr = new char; 2000 ? ptr *ptr =

Dynamically Allocated Data char* ptr; ptr = new char; 2000 ? ptr *ptr = ‘B’; cout delete << *ptr; NOTE: delete deallocates the memory pointed to by ptr 44

Using Operator delete returns to the free store memory which was previously allocated at

Using Operator delete returns to the free store memory which was previously allocated at run-time by operator new. The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. 45

Operator delete Syntax delete Pointer delete [ ] Pointer If the value of the

Operator delete Syntax delete Pointer delete [ ] Pointer If the value of the pointer is 0 there is no effect. Otherwise, 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. Square brackets are used with delete to deallocate a dynamically allocated array. 46

Dynamic Array Deallocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr,

Dynamic Array Deallocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; delete ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated // the value of ptr is undefined. ? ptr 47

What happens here? int* ptr = new int; *ptr = 3; 3 ptr =

What happens here? int* ptr = new int; *ptr = 3; 3 ptr = new int; *ptr = 4; // changes value of ptr 3 ptr 4 48

Inaccessible Object An inaccessible object is an unnamed object that was created by operator

Inaccessible Object An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it. int* ptr = new int; *ptr = 8; int* ptr 2 = new int; *ptr 2 = -5; 8 ptr -5 ptr 2 49

Making an Object Inaccessible int* ptr = new int; *ptr = 8; int* ptr

Making an Object Inaccessible int* ptr = new int; *ptr = 8; int* ptr 2 = new int; *ptr 2 = -5; 8 ptr -5 ptr 2 ptr = ptr 2; // here the 8 becomes inaccessible 8 ptr -5 ptr 2 50

Memory Leak A memory leak is the loss of available memory space that occurs

Memory Leak A memory leak is the loss of available memory space that occurs when dynamic data is allocated but never deallocated. 51

Leaving a Dangling Pointer A pointer that points to dynamic memory that has been

Leaving a Dangling Pointer A pointer that points to dynamic memory that has been de-allocated int* ptr = new int; *ptr = 8; int* ptr 2 = new int; *ptr 2 = -5; ptr = ptr 2; 8 ptr -5 ptr 2 delete ptr 2; // ptr is left dangling ptr 2 = NULL; 8 ptr NULL ptr 2 52

Why is a destructor needed? When a Dyn. Array class variable goes out of

Why is a destructor needed? When a Dyn. Array class variable goes out of scope, the memory space for data members size and pointer arr is deallocated. But the dynamic array that arr points to is not automatically deallocated. A class destructor is used to deallocate the dynamic memory pointed to by the data member. 53

class Dyn. Array Destructor Dyn. Array: : ~Dyn. Array( ); // Destructor. // POST:

class Dyn. Array Destructor Dyn. Array: : ~Dyn. Array( ); // Destructor. // POST: Memory for dynamic array deallocated. { delete [ ] arr ; } 54 54

Shallow Copy vs. Deep Copy a shallow copy copies only the class data members,

Shallow Copy vs. Deep Copy a shallow copy copies only the class data members, and does not make a copy of any pointed-to data a deep copy copies not only the class data members, but also makes a separate stored copy of any pointed-to data 55

Initialization of Class Objects C++ defines initialization to mean • initialization in a variable

Initialization of Class Objects C++ defines initialization to mean • initialization in a variable declaration • passing an object argument by value • returning an object as the return value of a function by default, C++ uses shallow copies for these initializations 56

As a result. . . when a class has a data member pointer to

As a result. . . when a class has a data member pointer to dynamically allocated data, you should write what is called a copy constructor the copy constructor is implicitly called in initialization situations and makes a deep copy of the dynamic data in a different memory location 57

Copy Constructors When there is a copy constructor provided for a class, the copy

Copy Constructors When there is a copy constructor provided for a class, the copy constructor is used to make copies for pass by value You do not call the copy constructor Like other constructors, it has no return type Because the copy constructor properly defines pass by value for your class, it must use pass by reference in its definition 58

Copy Constructor Copy constructor is a special member function of a class that is

Copy Constructor Copy constructor is a special member function of a class that is implicitly called in these 3 situations: • passing object parameters by value • initializing an object variable in its declaration • returning an object as the return value of a function 59

Classes with Data Member Pointers Need CONSTRUCTOR COPY CONSTRUCTOR DESTRUCTOR 60

Classes with Data Member Pointers Need CONSTRUCTOR COPY CONSTRUCTOR DESTRUCTOR 60

For the Final Exam Note: You will not have to write source code using

For the Final Exam Note: You will not have to write source code using pointers or dynamic memory. Questions related to these topics will be multiple choice or True/False 61

Recursive Function Call A recursive call is a function call in which the called

Recursive Function Call A recursive call is a function call in which the called function is the same as the one making the call In other words, recursion occurs when a function calls itself! But we need to avoid making an infinite sequence of function calls (infinite recursion) 62

Recursive Function Example void message() { cout << “This is a recursive function. n”;

Recursive Function Example void message() { cout << “This is a recursive function. n”; message(); } 63

Recursive Function Example The previous program will eventually crash, because each time a function

Recursive Function Example The previous program will eventually crash, because each time a function is called, temporary information is stored on a stack. The stack memory will eventually overflow and cause an error). A recursive function (as with a loop) must have some algorithm to control the number of times it repeats. void message(int times) { if(times > 0) { cout << “This is a recursive function. n”; message(times-1); } return; } 64

Finding a Recursive Solution The idea is for each successive recursive call to bring

Finding a Recursive Solution The idea is for each successive recursive call to bring you one step closer to a situation in which the problem can easily be solved This easily solved situation is called the base case Each recursive algorithm must have at least one base case, as well as a general (recursive) case 65

General format for Many Recursive Functions if (some easily-solved condition) // base case solution

General format for Many Recursive Functions if (some easily-solved condition) // base case solution statement else // general case recursive function call 66

Example Recursive Function Finding the Sum of the Numbers from 1 to n int

Example Recursive Function Finding the Sum of the Numbers from 1 to n int Summation ( int n ) { if ( n == 1) // base case return 1 ; else // general case return ( n + Summation ( n - 1 ) ) ; } 67

“Why use recursion? ” The previous example could have been written without recursion, by

“Why use recursion? ” The previous example could have been written without recursion, by using iteration instead. The iterative solution uses a loop, while the recursive solution uses an if statement. However, for certain problems the recursive solution is the most natural solution. This often occurs when structured variables are used. 68

For the Final Exam Note: You will not have to write source code using

For the Final Exam Note: You will not have to write source code using recursion. Questions related to this topics will be multiple choice or True/False 69

Final Exam Tues 3/16/10 (2 -3: 50) (Same classroom) Old Textbook - Chapters 11

Final Exam Tues 3/16/10 (2 -3: 50) (Same classroom) Old Textbook - Chapters 11 -16, 18 Focus is on 15, 16 and 18 Multiple choice, True/False and some minimal programming will be required 70