Programming Abstraction in C++ Eric S. Roberts and Julie Zelenski - - PowerPoint PPT Presentation

programming abstraction in c
SMART_READER_LITE
LIVE PREVIEW

Programming Abstraction in C++ Eric S. Roberts and Julie Zelenski - - PowerPoint PPT Presentation

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records Programming Abstraction in C++ Eric S. Roberts and Julie Zelenski Stanford University 2010 Enumeration Types Data and Memory Pointers Arrays Pointers and


slide-1
SLIDE 1

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Programming Abstraction in C++

Eric S. Roberts and Julie Zelenski

Stanford University 2010

slide-2
SLIDE 2

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Chapter 2. Data Types

slide-3
SLIDE 3

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-4
SLIDE 4

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Introduction

Goal: Hierarchy of data types. Building new data types from atomic data types.

slide-5
SLIDE 5

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Introduction

Goal: Hierarchy of data types. Building new data types from atomic data types. Mechanisms for creating new types: Pointers: Memory address of a value (may be an address itself). Arrays: Collection of data values of the same type. Accessed by indices. Records: Collection of data values (may be of different types). Identified by names.

slide-6
SLIDE 6

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-7
SLIDE 7

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types

Another atomic type defined by listing the elements in its domain.

  • Example. Definition

enum directionT {North, East, South, West} North, East, ...: Enumeration constants

slide-8
SLIDE 8

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types

Another atomic type defined by listing the elements in its domain.

  • Example. Definition

enum directionT {North, East, South, West} North, East, ...: Enumeration constants variable declaration directionT dir;

slide-9
SLIDE 9

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types (cont.)

Assigning integers to enumeration constants: Automatic North= 0, East= 1, ...

slide-10
SLIDE 10

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types (cont.)

Assigning integers to enumeration constants: Automatic North= 0, East= 1, ... manual

enum coinT { Penny = 1, Nickel = 5, Dime = 10, Quarter = 25 };

slide-11
SLIDE 11

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types (cont.)

semi-automatic

enum monthT { January = 1, February, March, April, May, June, July, August, September, October, November, December };

slide-12
SLIDE 12

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types (cont.)

semi-automatic

enum monthT { January = 1, February, March, April, May, June, July, August, September, October, November, December };

You can perform integer operations on values of an enumeration type Example

directionT RightFrom(directionT dir) { return directionT((dir + 1) % 4); }

slide-13
SLIDE 13

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Enumeration types (cont.)

semi-automatic

enum monthT { January = 1, February, March, April, May, June, July, August, September, October, November, December };

You can perform integer operations on values of an enumeration type Example

directionT RightFrom(directionT dir) { return directionT((dir + 1) % 4); }

A general type class: scalar types (enumeration types, characters, and various representations of integers). Implicit conversion from a value of a scalar type into an integer.

slide-14
SLIDE 14

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-15
SLIDE 15

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Data and memory

Memory units: bit (smallest) byte (typically 8 bits, size of char) word (size of int, 2 bytes or 4 bytes or others)

slide-16
SLIDE 16

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Data and memory

Memory units: bit (smallest) byte (typically 8 bits, size of char) word (size of int, 2 bytes or 4 bytes or others) Memory addresses: Byte addressable, starting from 0

slide-17
SLIDE 17

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Data and memory

Memory units: bit (smallest) byte (typically 8 bits, size of char) word (size of int, 2 bytes or 4 bytes or others) Memory addresses: Byte addressable, starting from 0 sizeof operator usage: sizeof(int) sizeof x returns the number of bytes.

slide-18
SLIDE 18

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

  • Example. Memory allocation

char ch; ch = ’A’; ch 1000 1001 1002 65

slide-19
SLIDE 19

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example (cont.)

int i; i = 123;

i 1000 1004 123

slide-20
SLIDE 20

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-21
SLIDE 21

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

Pointer: An address in memory, typically four bytes, for memory

  • f size up to 4GB.
slide-22
SLIDE 22

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

Pointer: An address in memory, typically four bytes, for memory

  • f size up to 4GB.

lvalue: An expression that refers to an internal memory location (can appear on the left side of an assignment). lvalues: simple variables, x = 1.0 not lvalues: constants, arithmetic expressions (x + 1)

slide-23
SLIDE 23

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

Pointer variables int *p; pointer-to-int, base type is int char *cptr; pointer-to-char, base type is char

slide-24
SLIDE 24

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

Pointer variables int *p; pointer-to-int, base type is int char *cptr; pointer-to-char, base type is char Operator & (address-of) &x memory address in which x (lvalue) is stored.

slide-25
SLIDE 25

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

  • Example. * and &

int x, y; (lvalues) int *p1, *p2; (pointer-to-int) p2 1000 1004 1008 1012 x y p1

slide-26
SLIDE 26

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

  • Example. * and &

int x, y; (lvalues) int *p1, *p2; (pointer-to-int) p2 1000 1004 1008 1012 x y p1 &x is 1000, &y is 1004

slide-27
SLIDE 27

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

  • Example. * and &

x = -42; y = 163; p1 = &x; p2 = &y;

1004

1000 1004 1008 1012 x y p1 p2

−42 163 1000

slide-28
SLIDE 28

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

  • Example. * and &

Dereferencing *p1 = 17

17

1000 1004 1008 1012 x y p1 p2

163 1000 1004

slide-29
SLIDE 29

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

  • Example. * and &

Pointer assignment and value assignment p1 = p2; and *p1 = *p2; 1000 1004 1008 1012 x y p1 p2

163 17 1004

1004

163

1000 1004 1008 1012 x y p1 p2

163 1000 1004

slide-30
SLIDE 30

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

null pointer NULL A special value that does not point to any valid data.

slide-31
SLIDE 31

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

null pointer NULL A special value that does not point to any valid data. Do not dereference a null pointer (do not use *NULL)

slide-32
SLIDE 32

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers

null pointer NULL A special value that does not point to any valid data. Do not dereference a null pointer (do not use *NULL) Do not use pointer variables whose values have not yet been initialized.

slide-33
SLIDE 33

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-34
SLIDE 34

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Arrays

An array is characterized by element type; array size (number of elements).

slide-35
SLIDE 35

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Arrays

An array is characterized by element type; array size (number of elements). Declaration type name[size]

slide-36
SLIDE 36

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Arrays

An array is characterized by element type; array size (number of elements). Declaration type name[size] style Define a constant for array size.

slide-37
SLIDE 37

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Arrays

Example const int N_JUDGES = 5; double scores[N_JUDGES]; Element selection scores[0] = 9.2; array name and index

slide-38
SLIDE 38

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Passing arrays as parameters

Example. double Mean(double array[], int n) { double total = 0; for (int i = 0; i < n; i++) { total += array[i]; } return total / n; }

slide-39
SLIDE 39

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Passing arrays as parameters

Example. double Mean(double array[], int n) { double total = 0; for (int i = 0; i < n; i++) { total += array[i]; } return total / n; } use empty brackets (a pointer to the array, elements can be modified); pass the effective size as a parameter.

slide-40
SLIDE 40

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example: gymjudge.cpp, p. 61

/* * File: gymjudge.cpp * ------------------ * This program averages a set of gymnastic scores. */ #include <iostream> #include "genlib.h" #include "simpio.h"

slide-41
SLIDE 41

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example: gymjudge.cpp

/* constants */ const int MAX_JUDGES = 100; const double MIN_SCORE = 0.0; const double MAX_SCORE = 10.0; /* Private function prototypes */ void ReadAllScores(double scores[], int nJudges); double GetScores(int judge); double Mean(double array[], int n);

slide-42
SLIDE 42

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example: gymjudge.cpp

int main() { double scores[MAX_JUDGES]; cout << "Enter number of judges: " << endl; int nJudges = GetInteger(); if (nJudges > MAX_JUDGES) Error("Too many judges"); ReadAllScores(scores, nJudges); cout << "The average score is " << Mean(scores, nJudges) << endl; return 0; }

slide-43
SLIDE 43

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example: gymjudge.cpp

int main() { double scores[MAX_JUDGES]; cout << "Enter number of judges: " << endl; int nJudges = GetInteger(); if (nJudges > MAX_JUDGES) Error("Too many judges"); ReadAllScores(scores, nJudges); cout << "The average score is " << Mean(scores, nJudges) << endl; return 0; }

Remarks Basic structure: Declaration and initialization - input - compute - output; Robustness: Handle all possible inputs.

slide-44
SLIDE 44

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example: gymjudge.cpp

/* * Function: ReadAllScores ... */ void ReadAllScores(double scores[], int nJudges) { for (int i = 0; i < nJudges; i++) { scores[i] = GetScore(i + 1); } }

Use empty brackets when passing an array as a parameter (pointer). Elements are modified.

slide-45
SLIDE 45

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Example: gymjudge.cpp

/* * Function: GetScore ... */ double GetScore(int judge) { while (true) { cout << "Score for judge #" << judge << ": " << endl; double score = GetReal(); if (score >= MIN_SCORE && score <= MAX_SCORE) return score; cout << "That score is out of range. Try again." << endl; } }

Robustness, bullet-proof your program; Loop-and-half structure.

slide-46
SLIDE 46

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Multidimensional arrays

Array of arrays.

slide-47
SLIDE 47

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Multidimensional arrays

Array of arrays. Two-dimensional arrays for matrices (rectangle structure). Example: double mat[3][2] An array of three arrays, each of which is an array of two floating-point numbers, representing a three-by-two matrix.

slide-48
SLIDE 48

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Multidimensional arrays (cont.)

Internal structure (row orientation)

mat[2][1] mat[0][0] mat[0][1] mat[1][0] mat[1][1] mat[2][0]

slide-49
SLIDE 49

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Initializing arrays

double mat[3][2] = { { 1.0, 2.0 }, { 2.0, 1.0 }, { 3.0, 2.0 } };

matrix:   1.0 2.0 2.0 1.0 3.0 2.0  

slide-50
SLIDE 50

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Multidimensional arrays (cont.)

In C++, it is more efficient to access elements in rows than in columns.

for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { ... mat[i][j] ... } }

is more efficient than

for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { ... mat[i][j] ... } }

slide-51
SLIDE 51

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-52
SLIDE 52

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers and arrays

int intList[5]; intList is identical to &intList[0] &intList[i] is the same as intList + i*sizeof(int) the prototype int SumIntArray(int array[], int n) works the same way as int SumIntArray(int *array, int n) int intList[5] allocates five consecutive words, whereas int *p allocates one word for an address a pointer allows you to create a new array as the program runs (dynamic allocation, later)

slide-53
SLIDE 53

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Outline

1

Enumeration Types

2

Data and Memory

3

Pointers

4

Arrays

5

Pointers and Arrays

6

Records

slide-54
SLIDE 54

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Records

A coherent collection of components of possibly different types. Each of these components is called a field or member of the record.

slide-55
SLIDE 55

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Records

A coherent collection of components of possibly different types. Each of these components is called a field or member of the record. Defining a new structured type

1

Define a structure, Including fields, names and types of the

  • fields. This structure defines a model, but does not reserve

any storage;

struct employeeRecordT { string name; string title; string ssn; double salary; int withholding; };

2

Declare variables of the new type.

employeeRecordT empRec;

slide-56
SLIDE 56

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Records

Field selection empRec.title (recordName.fieldName) an lvalue

slide-57
SLIDE 57

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Records

Field selection empRec.title (recordName.fieldName) an lvalue Initializing records

empRec.name = "Ebenezer Scrooge"; empRec.title = ...

  • r

employeeRecordT empRec = { "Ebenezer Scrooge", ... };

slide-58
SLIDE 58

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers to records

Often variables that hold structured data are declared to be pointers to records. employeeRecordT *empPtr;

slide-59
SLIDE 59

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers to records

Often variables that hold structured data are declared to be pointers to records. employeeRecordT *empPtr; Field selection empPtr->salary means (*empPtr).salary

slide-60
SLIDE 60

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Pointers to records

Often variables that hold structured data are declared to be pointers to records. employeeRecordT *empPtr; Field selection empPtr->salary means (*empPtr).salary What does *empPtr.salary mean?

slide-61
SLIDE 61

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Allocation

Static allocation: Global variables that persist throughout the entire program. Automatic allocation: Local variables inside a function, allocated on the system stack and freed when the function returns. Dynamic allocation: Variables created while the program is running, allocated on the heap, the pool of memory available to a program.

slide-62
SLIDE 62

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Allocation

Example

employeeRecordT *empList = new employeeRecordT[1000];

slide-63
SLIDE 63

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Allocation

Example

employeeRecordT *empList = new employeeRecordT[1000];

Allocates an array of 1000 employee records in the heap and returns the pointer to the first record.

slide-64
SLIDE 64

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Deallocation

Coping with memory limitations. Free pieces of memory when you are finished using them. double *dptr = new double; int *arr = new int[45]; ... delete dptr; delete[] arr;

slide-65
SLIDE 65

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Deallocation

Coping with memory limitations. Free pieces of memory when you are finished using them. double *dptr = new double; int *arr = new int[45]; ... delete dptr; delete[] arr; Don’t worry about it for this course.

slide-66
SLIDE 66

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Examples

Declared arrays and dynamic arrays double dblArray[10]; Memory is allocated automatically as part of declaration

  • process. The elements are allocated as part of the frame for

the function (on the stack). The size must be a constant.

slide-67
SLIDE 67

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Examples

Declared arrays and dynamic arrays double dblArray[10]; Memory is allocated automatically as part of declaration

  • process. The elements are allocated as part of the frame for

the function (on the stack). The size must be a constant. double *dblList; dblList = new double[10]; Memory is not allocated until new is invoked. The elements are allocated on the heap. The size can be a variable.

slide-68
SLIDE 68

Enumeration Types Data and Memory Pointers Arrays Pointers and Arrays Records

Examples (cont.)

Dynamic array of n pointers to employeeRecordT employeeRecordT **list; list = new employeeRecordT*[n]; list[0] = new employeeRecordT;