Review Fall 2017 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2017 CISC2200 Yanjun Li 2 1
Computer Fall 2017 CISC2200 Yanjun Li 3 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory locations. Fall 2017 CISC2200 Yanjun Li 4 2
Elements of An Array To refer to a particular location or element in the array, we specify the name of the array and the index of the element. The index must be integer or integer expression, its value must be larger than or equal to 0. First element has index zero. The element could be used as a variable. Example C[ 0 ] += 2; C[ a + b ] = 3; Fall 2017 CISC2200 Yanjun Li 5 Example An array c has 12 elements ( c[0], c[1], c[11] ); the value of c[0] is 45. Fall 2017 CISC2200 Yanjun Li 6 3
Declare An Array Declaration of an array: type arrayname[ arraysize ]; Example int c[ 12 ]; Array s size must be an integer constant greater than zero. Arrays can be declared to contain values of data types like int, float, double, char, etc. Fall 2017 CISC2200 Yanjun Li 7 Initialize An Array (1) With an initializer list Initializer list Items enclosed in braces ({}) and separated by commas. Examples int n[ 5 ] = { 10, 20, 30, 40, 50 }; int m[ 5 ] = { 10, 20, 30 }; The remaining elements are initialized to zero. int p[ ] = { 10, 20, 30, 40, 50 }; Because array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list. Fall 2017 CISC2200 Yanjun Li 8 4
Initialize An Array (2) Using a loop to initialize the array s elements Declare array, specify number of elements Use repetition statement to loop for each element Example: int n[10]; for ( int i = 0; i < 10; i++) { n[ i ] = 0; } Fall 2017 CISC2200 Yanjun Li 9 Using An Array Usually use for loop to access each element of an array. C++ has no array bounds checking Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. You need to provide the correct array size. Fall 2017 CISC2200 Yanjun Li 10 5
Using An Array Example 1 Summing the elements of an array Example: const int arraysize = 6; int a [ arraysize ] = { 87, 69, 45, 45, 43, 21 }; int total = 0; for ( int i = 0; i < arraysize; i++) { total += a[i]; } cout << Total of array elements is <<total<<endl; Fall 2017 CISC2200 Yanjun Li 11 C++ Tips for Function Call 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 Fall 12 2017 CISC2200 Yanjun Li 12 6
C++ Tips for Function Call Pass-by-reference sends the location (memory address) of the actual parameter CALLING BLOCK FUNCTION CALLED SO, the actual parameter can be changed by the function Fall 2017 13 CISC2200 Yanjun Li 13 Passing Arrays as Parameters In C++, arrays are always passed by reference, and & is not used with the formal parameter type. Whenever an array is passed as a parameter, its base address is sent to the called function. Example: // prototype float SumValues ( float values [ ], int numofvalues ); Fall 2017 CISC2200 Yanjun Li 14 7
const array parameter Because arrays are always passed as reference parameters, you can protect the actual parameter from unintentional changes by using const in formal parameter list and function prototype. FOR EXAMPLE... // prototype float SumValues(const float values[ ], int numofvalues ); Fall 2017 CISC2200 Yanjun Li 15 // Pre: values[0] through values[numofvalues-1] // have been assigned // Returns the sum of values[0] through // values[numofvalues-1] float SumValues (const float values[ ], int numofvalues ) { float sum = 0; for ( int index = 0; index < numofvalues; index++ ) { sum += values [ index ] ; } } return sum; Fall 2017 CISC2200 Yanjun Li 16 8
Multidimensional Array Multidimensional arrays with two dimensions Called two dimensional or 2-D arrays Represent tables of values with rows and columns Elements referenced with two subscripts ([x][y]) In general, an array with m rows and n columns is called an m-by-n array Multidimensional arrays can have more than two dimensions Fall 2017 CISC2200 Yanjun Li 17 Declaring & Initializing Two-Dimensional Arrays Declaring two-dimensional array b int b[ 3 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[ 0 ][ 0 ] and b[ 0 ][ 1 ] 3 and 4 initialize b[ 1 ][ 0 ] and b[ 1 ][ 1 ] 0 and 0 initialize b[ 2 ][ 0 ] and b[ 2 ][ 1 ] (implicitly). Column 0 Column 1 Row 0 1 2 Row 1 3 4 Row 2 0 0 Fall 2017 CISC2200 Yanjun Li 18 9
Two-Dimensional Array Fall 2017 CISC2200 Yanjun Li 19 Passing Multidimensional Arrays to Functions Multidimensional array parameters Size of first dimension is not required As with a one-dimensional array Size of subsequent dimensions are required Compiler must know how many elements to skip to move to the second element in the first dimension Example void printarray( const int a[][ 3 ] ); Function will skip row 0 s 3 elements to access row 1 s elements (a[ 1 ][ x ]) Fall 2017 CISC2200 Yanjun Li 20 10
Implementation Level View statehighs[ 0 ] [ 0 ] statehighs[ 0 ] [ 1 ] statehighs[ 0 ] [ 2 ] statehighs[ 0 ] [ 3 ] statehighs[ 0 ] [ 4 ] statehighs[ 0 ] [ 5 ] statehighs[ 0 ] [ 6 ] statehighs[ 0 ] [ 7 ] statehighs[ 0 ] [ 8 ] statehighs[ 0 ] [ 9 ] statehighs[ 0 ] [10 ] statehighs[ 0 ] [11 ] statehighs[ 1 ] [ 0 ] statehighs[ 1 ] [ 1 ] statehighs[ 1 ] [ 2 ] statehighs[ 1 ] [ 3 ]... Base Address 8000 To locate an element such as statehighs [ 2 ] [ 7] the compiler needs to know that there are 12 columns in this two-dimensional array. At what address will statehighs [ 2 ] [ 7 ] be found? Assume 2 bytes for type int. Fall 2017 CISC2200 Yanjun Li 21 Multidimensional-Array Manipulations Commonly performed with for statements Example Modify all elements in a row for ( int col = 0; col < 4; col++ ) a[ 2 ][ col ] = 0; Example Total all elements total = 0; for ( int row = 0; row < 3; row++ ) for ( int col = 0; col < 4; col++ ) total += a[ row ][ col ]; Fall 2017 CISC2200 Yanjun Li 22 11
Pointer Types Pointer variable A variable whose value is the address of a location in memory int* intpointer Fall 2017 CISC2200 Yanjun Li 23 int alpha; int* intpointer; intpointer = α Pointer Types If alpha is at address 33, memory looks like this Fall 2017 CISC2200 Yanjun Li 24 12
Pointer Types int x; x = 12; 2000 x 12 int* ptr; ptr = &x; 3000 ptr 2000 NOTE: Because ptr holds the address of x, we say that ptr points to x Fall 2017 CISC2200 Yanjun Li 25 Pointer Types Dereference operator (*) An operator that, when applied to a pointer variable, denotes the variable to which the pointer points Fall 2017 CISC2200 Yanjun Li 26 13
Pointer Types int x; x = 12; int* ptr; ptr = &x; std::cout << *ptr; 3000 ptr 2000 2000 x 12 *ptr is the value in the place to which ptr points Fall 2017 CISC2200 Yanjun Li 27 Pointer Types int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at adddress ptr to 5 3000 2000 ptr 2000 12 5 x Fall 2017 CISC2200 Yanjun Li 28 14
char ch; ch = A ; char* q; q = &ch; *q = Z ; char* p; p = q; Pointer Types 4000 A Z ch 5000 6000 4000 4000 q p // the right side has value 4000 // now p and q both point to ch Fall 2017 CISC2200 Yanjun Li 29 Pointer Types Dynamic allocation (new operator) Allocation of memory space for a variable at run time (as opposed to static allocation at compile time) Fall 2017 CISC2200 Yanjun Li 30 15
Pointer Types int * intpointer; intpointer = new int; Fall 2017 CISC2200 Yanjun Li 31 NULL Pointer Pointer Types A pointer that points to nothing; available in <cstdlib> NULL is defined to be 0; But NULL is not memory address 0; int * intptr = NULL; Float * money = NULL; intptr money Fall 2017 CISC2200 Yanjun Li 32 16
Pointer Types Memory Leak The loss of available memory space that occurs when memory is allocated dynamically but never deallocated float * mymoney = new float; float * money = new float; mymoney = money; //wrong Garbage Memory locations that can no longer be accessed To avoid memory leaks, use delete. delete mymoney; //correct mymoney = money; Fall 2017 CISC2200 Yanjun Li 33 Pointer and Array Dynamically create array with pointers int * foo; foo = new int[5]; delete [] foo; The system dynamically allocate space for 5 elements of type int and returns the memory address of the first element of the array, which is assigned to foo (the pointer). Fall 2017 CISC2200 Yanjun Li 34 17
Object-Oriented Programming objects, sending a message, methods, instance variables. Object An instance of a class Method A public member function of a class Instance variable (Data Member) A private data member of a class Fall 2017 CISC2200 Yanjun Li 35 C++ class data type A class is an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them. Fall 2017 CISC2200 Yanjun Li 36 18
class DateType Specification // SPECIFICATION FILE ( datetype.h ) class DateType { public : // declares a class data type // 4 public member functions DateType (int newmonth,int newday,int newyear);//constructor int getyear( ) const ; // returns year int getmonth( ) const ; // returns month int getday( ) const ; // returns day private : // 3 private data members int year ; int month ; int day ; } ; Fall 2017 CISC2200 Yanjun Li 37 37 2 separate files for class type // SPECIFICATION FILE ( datetype.h ) // Specifies the data and function members. class DateType { public:... private:... } ; // IMPLEMENTATION FILE ( datetype.cpp ) // Implements the DateType member functions.... Fall 2017 CISC2200 Yanjun Li 38 19
Code Using DateType #include datetype.h //includes specification of the class #include <iostream> using namespace std; int main ( ) { // declares 2 objects of DateType DateType startdate ( 6, 30, 1998 ) ; DateType enddate ( 10, 31, 2002 ) ; bool retired = false ; } cout << startdate.getmonth( )<< / << startdate.getday( ) << / << startdate.getyear( ) << endl; while (! retired ) { finishsometask( ) ;... } return 0; Fall 2017 CISC2200 Yanjun Li 39 39 Implementation of member functions // IMPLEMENTATION FILE (datetype.cpp) #include datetype.h // also must appear in client code DateType :: DateType ( int newmonth, int newday, int newyear ) // Post: year is set to newyear. // month is set to newmonth. // day is set to newday. { year = newyear ; month = newmonth ; day = newday ; } Fall 2017 CISC2200 Yanjun Li 40 40 20
int DateType :: getmonth ( ) const // Accessor function for data member month { return month ; } int DateType :: getyear ( ) const // Accessor function for data member year { return year ; } int DateType :: getday ( ) const // Accessor function for data member day { return day ; } Fall 2017 CISC2200 Yanjun Li 41 41 Object-Oriented Programming Three ingredients in any object-oriented language encapsulation inheritance polymorphism Just as a capsule protects its contents, the class construct protects its data members, but what are inheritance and polymorphism? Fall 2017 CISC2200 Yanjun Li 42 21
Object-Oriented Programming Inheritance A mechanism used with a hierarchy of classes in which each descendant class inherits the properties (data and operations) of its ancestor class Base class The class being inherited from Derived class the class that inherits Fall 2017 CISC2200 Yanjun Li 43 Object-Oriented Programming Inheritance is an "is-a" relationship: a wheeled vehicle is a vehicle; a bicycle is a wheeled vehicle a four-door car is a car Fall 2017 CISC2200 Yanjun Li 44 22
Object-Oriented Programming Overriding Function with virtual keyword in base class. Derived classes override function as appropriate. An overridden function in a derived class has the same signature and return type (i.e. prototype) as the function it overrides in its base class. Polymorphism The ability to determine which of several operations with the same name is appropriate; a combination of static and dynamic binding Fall 2017 CISC2200 Yanjun Li 45 Object-Oriented Programming Person Employee Manager Each class has a method Print Person.Print just prints the name Employee.Print prints the name and job title Manager.Print prints name, job title, and department Print is overriden. Static binding is when the compiler can tell which Print to use; dynamic binding is when the determination cannot be made until run time Fall 2017 CISC2200 Yanjun Li 46 23
Object-Oriented Programming Inheritance and polymorphism work together How? They combine to allow the programmer to build useful hierarchies of classes that can be put into a library to be reused in different applications Fall 2017 CISC2200 Yanjun Li 47 Reference Reproduced from C++ Plus Data Structures, 4 th edition by Nell Dale. Reproduced by permission of Jones and Bartlett Publishers International. Fall 2017 CISC2200 Yanjun Li 48 24