Review of C++ Programming Part I Sheng-Fang Huang
Random Number Generation C++ Standard Library function rand –Introduces the element of chance into computer applications –Example i = rand(); –Generates an unsigned integer between 0 and RAND_MAX (a symbolic constant defined in header file ) –Function prototype for the rand function is in
Random Number Generation To produce integers in a specific range, use the modulus operator ( % ) with rand –Example rand() % 6; –Produces numbers in the range 0 to 5 –This is called scaling, 6 is the scaling factor –Shifting can move the range to 1 to rand() % 6;
#include and using for function rand Calling function rand
Random Number Generation Function rand –Generates pseudorandom numbers –The same sequence of numbers repeats itself each time the program executes Randomizing –Conditioning a program to produce a different sequence of random numbers for each execution C++ Standard Library function srand –Takes an unsigned integer argument –Seeds the rand function to produce a different sequence of random numbers
using statement for function srand Data type unsigned is short for unsigned int Passing seed to srand to randomize the program
Program outputs show that each unique seed value produces a different sequence of random numbers
Random Number Generation To randomize without having to enter a seed each time –srand(time(0)); This causes the computer to read its clock to obtain the seed value –Function time (with the argument 0 ) Returns the current time as the number of seconds since January 1, 1970 at midnight Greenwich Mean Time (GMT) Function prototype for time is in
Random Number Generation Common Programming Error –Calling function srand more than once in a program restarts the pseudorandom number sequence and can affect the randomness of the numbers produced by rand. –Using srand in place of rand to attempt to generate random numbers is a compilation error—function srand does not return a value.
References and Reference Parameters Two ways to pass arguments to functions –Pass-by-value A copy of the argument’s value is passed to the called function Changes to the copy do not affect the original variable’s value in the caller –Prevents accidental side effects of functions –Pass-by-reference Gives called function the ability to access and modify the caller’s argument data directly
References and Reference Parameters Reference Parameter –An alias for its corresponding argument in a function call –& placed after the parameter type in the function prototype and function header –Example int &count in a function header –Pronounced as “ count is a reference to an int ” –Parameter name in the body of the called function actually refers to the original variable in the calling function
References and Reference Parameters Pass-by-reference is good for performance reasons, because it can eliminate the pass-by-value overhead of copying large amounts of data. Pass-by-reference can weaken security, because the called function can corrupt the caller’s data.
Function illustrating pass-by-value Function illustrating pass-by-reference Variable is simply mentioned by name in both function calls
Receives copy of argument in main Receives reference to argument in main Modifies variable in main
References and Reference Parameters For the combined reasons of clarity and performance, many C++ programmers prefer that modifiable arguments be passed to functions by using pointers (which we study in Chapter 8), small nonmodifiable arguments be passed by value and large nonmodifiable arguments be passed to functions by using references to constants.
References and Reference Parameters References –Can also be used as aliases for other variables within a function All operations supposedly performed on the alias (i.e., the reference) are actually performed on the original variable An alias is simply another name for the original variable Must be initialized in their declarations –Cannot be reassigned afterward –Example int count = 1; int &cRef = count; cRef++; –Increments count through alias cRef
Creating a reference as an alias to another variable in the function Assign 7 to x through alias y
Uninitialized reference
References and Reference Parameters Returning a reference from a function –Functions can return references to variables Should only be used when the variable is static –Dangling reference Returning a reference to an automatic variable –That variable no longer exists after the function ends
Common Programming Error Not initializing a reference variable when it is declared is a compilation error, unless the declaration is part of a function’s parameter list. Reference parameters are initialized when the function in which they are declared is called.
Common Programming Error Attempting to reassign a previously declared reference to be an alias to another variable is a logic error. The value of the other variable is simply assigned to the variable for which the reference is already an alias.
Common Programming Error Returning a reference to an automatic variable in a called function is a logic error. Some compilers issue a warning when this occurs.
Recursion Recursive function –A function that calls itself. Recursion –Base case(s) The simplest case(s), which the function knows how to handle –For all other cases, the function typically divides the problem into two conceptual pieces A piece that the function knows how to do A piece that it does not know how to do –Slightly simpler or smaller version of the original problem
Recursion Recursion (Cont.) –Recursive call (also called the recursion step) The function launches (calls) a fresh copy of itself to work on the smaller problem Can result in many more recursive calls, as the function keeps dividing each new problem into two conceptual pieces This sequence of smaller and smaller problems must eventually converge on the base case –Otherwise the recursion will continue forever
Recursion Factorial –The factorial of a nonnegative integer n, written n! (and pronounced “n factorial”), is the product n · (n – 1) · (n – 2) · … · 1 –Recursive definition of the factorial function n! = n · (n – 1)! Example 5! = 5 · 4 · 3 · 2 · 1 5! = 5 · ( 4 · 3 · 2 · 1) 5! = 5 · ( 4! )
Recursive evaluation of 5!.
First call to factorial function
Base cases simply return 1 Recursive call to factorial function with a slightly smaller problem
Arrays Array –Consecutive group of memory locations All of which have the same type –Index Position number used to refer to a specific location/element Also called subscript Place in square brackets –Must be positive integer or integer expression First element has index zero Example (assume a = 5 and b = 6 ) –c[ a + b ] += 2; »Adds 2 to array element c[ 11 ]
Fig.7.1 | Array of 12 elements Examine array c –c is the array name –c has 12 elements ( c[0], c[1], … c[11] ) The value of c[0] is –45 Brackets used to enclose an array subscript are actually an operator in C++.
7.4 Examples Using Arrays Using a loop to initialize the array’s elements –Declare array, specify number of elements –Use repetition statement to loop for each element Use body of repetition statement to initialize each individual array element
Examples Using Arrays Initializing an array in a declaration with an initializer list –If fewer initializers than elements in the array Remaining elements are initialized to zero Example –int n[ 10 ] = { 0 }; –If more initializers than elements in the array Compilation error
Declare n as an array of int s Compiler uses initializer list to initialize array
Examples Using Arrays Specifying an array’s size with a constant variable and setting array elements with calculations –Initialize elements of 10-element array to even integers –Use repetition statement that calculates value for current element, initializes array element using calculated value
Declare constant variable arraySize using the const keyword Declare array that contains 10 int s
Examples Using Arrays Using character arrays to store and manipulate strings –Arrays may be of any type, including char s We can store character strings in char arrays –Can be initialized using a string literal Example –char string1[] = "Hi"; Equivalent to –char string1[] = { 'H', 'i', '\0' }; –Array contains each character plus a special string- termination character called the null character ( '\0' )
Examples Using Arrays Using character arrays to store and manipulate strings (Cont.) –Can also be initialized with individual character constants in an initializer list char string1[] = { 'f', 'i', 'r', 's', 't', '\0' }; –Can also input a string directly into a character array from the keyboard using cin and >> cin >> string1; cin >> may read more characters than the array can store –A character array representing a null- terminated string can be output with cout and <<
Store "string literal" as an array of characters Initializing an array of characters using cin Accessing specific characters in the array Loop until the terminating null character is reached
Examples Using Arrays static local arrays and automatic local arrays –A static local variable in a function Exists for the duration of the program But is visible only in the function body –A static local array Exists for the duration of the program Is initialized when its declaration is first encountered –All elements are initialized to zero if not explicitly initialized »This does not happen for automatic local arrays
Create a static array using keyword static Create an automatic local array
Values reflect changes from the previous function call – the array was not reinitialized
Pointer Variable Pointer variables –Contain memory addresses as values Normally, variable contains specific value (direct reference) Pointers contain address of variable that has specific value (indirect reference) Indirection –Referencing value through pointer
Pointer Variable Declarations and Initialization Pointer declarations –* indicates variable is a pointer Example –int *myPtr; »Declares pointer to int, of type int * Multiple pointers require multiple asterisks int *myPtr1, *myPtr2; Pointer initialization –Initialized to 0, NULL, or an address 0 or NULL points to nothing (null pointer)
Pointer Variable Declarations and Initialization number1 45 number2 30 number1 number2 int number1; int *number1;
Directly and indirectly referencing a variable.
Pointer Operators Address operator ( & ) –Returns memory address of its operand –Example int y = 5; int *yPtr; yPtr = &y; assigns the address of variable y to pointer variable yPtr –Variable yPtr “points to” y »yPtr indirectly references variable y ’s value
Pointer Operators * operator –Also called indirection operator or dereferencing operator –*yPtr returns y (because yPtr points to y ) –Dereferenced pointer can be an lvalue *yptr = 9; * and & are inverses of each other
Common Programming Error Dereferencing a pointer that has not been properly initialized or that has not been assigned to point to a specific location in memory could cause a fatal execution-time error, or it could accidentally modify important data and allow the program to run to completion, possibly with incorrect results.
Common Programming Error An attempt to dereference a variable that is not a pointer is a compilation error. Dereferencing a null pointer is normally a fatal execution-time error.
* and & are inverses of each other Address of a and the value of aPtr are identical * and & are inverses; same result when both are applied to aPtr Value of a and the dereferenced aPtr are identical Outline Variable aPtr is a point to an int Initialize aPtr with the address of variable a
Passing Arguments to Functions by Reference with Pointers Three ways to pass arguments to a function –Pass-by-value –Pass-by-reference with reference arguments –Pass-by-reference with pointer arguments A function can return only one value Arguments passed to a function using reference arguments –Function can modify original values of arguments More than one value “returned”
Passing Arguments to Functions by Reference with Pointers Pass-by-reference with pointer arguments –Simulates pass-by-reference Use pointers and indirection operator –Pass address of argument using & operator –Arrays not passed with & because array name is already a pointer –* operator used as alias/nickname for variable inside of function
Outline Pass number by value; result returned by cubeByValue cubeByValue receives parameter passed-by-value Cubes local variable n and return the result
Outline Prototype indicates parameter is a pointer to an int Apply address operator & to pass address of number to cubeByReference cubeByReference modifies variable number cubeByReference receives address of an int variable, i.e., a pointer to an int Modify and access int variable using indirection operator *
Using const with Pointers Four ways to pass pointer to function –Nonconstant pointer to nonconstant data Highest amount of access Data can be modified through the dereferenced pointer Pointer can be modified to point to other data –Pointer arithmetic »Operator ++ moves array pointer to the next element Its declaration does not include const qualifier
Using const with Pointers –Nonconstant pointer to constant data Pointer can be modified to point to any appropriate data item Data cannot be modified through this pointer Provides the performance of pass-by-reference and the protection of pass-by-value
Outline Parameter is a nonconstant pointer to constant data Pass pointer phrase to function printCharacters sPtr is a nonconstant pointer to constant data; it cannot modify the character to which it points Increment sPtr to point to the next character
Outline Parameter is a nonconstant pointer to constant data Pass the address of int variable y to attempt an illegal modification
Outline Attempt to modify a const object pointed to by xPtr Error produced when attempting to compile Pass large objects using pointers to constant data, or references to constant data, to obtain the security of pass-by-value.
Using const with Pointers –Constant pointer to nonconstant data Always points to the same memory location –Can only access other elements using subscript notation Data can be modified through the pointer Default for an array name –Can be used by a function to receive an array argument Must be initialized when declared
Outline ptr is a constant pointer to an integer Can modify x (pointed to by ptr ) since x is not constant Cannot modify ptr to point to a new address since ptr is constant Line 14 generates a compiler error by attempting to assign a new address to a constant pointer
Using const with Pointers –Constant pointer to constant data Least amount of access Always points to the same memory location Data cannot be modified using this pointer
Outline ptr is a constant pointer to a constant integer Cannot modify x (pointed to by ptr ) since *ptr is constant Cannot modify ptr to point to a new address since ptr is constant
Pointer Expressions and Pointer Arithmetic Pointer arithmetic –Increment/decrement pointer ( ++ or -- ) –Add/subtract an integer to/from a pointer ( + or +=, - or -= ) –Pointer arithmetic is meaningless unless performed on a pointer to an array
Pointer Expressions and Pointer Arithmetic 5 element int array on a machine using 4 byte int s –vPtr points to first element v[ 0 ], at location 3000 vPtr = &v[ 0 ]; –vPtr += 2; sets vPtr to 3008 ( * 4 ) vPtr points to v[ 2 ]
Array v and a pointer variable vPtr that points to v. after pointer arithmetic
Relationship Between Pointers and Arrays Arrays and pointers are closely related –Array name is like constant pointer –Pointers can do array subscripting operations
Relationship Between Pointers and Arrays Accessing array elements with pointers –Assume declarations: int b[ 5 ]; int *bPtr; bPtr = b; –Element b[ n ] can be accessed by *( bPtr + n ) Called pointer/offset notation –Addresses &b[ 3 ] is same as bPtr + 3 –Array name can be treated as pointer b[ 3 ] is same as *( b + 3 ) –Pointers can be subscripted (pointer/subscript notation) bPtr[ 3 ] is same as b[ 3 ]
Common Programming Error 8.14 Although array names are pointers to the beginning of the array and pointers can be modified in arithmetic expressions, array names cannot be modified in arithmetic expressions, because array names are constant pointers. For clarity, use array notation instead of pointer notation when manipulating arrays.
Outline Using array subscript notation Using array name and pointer/offset notation
Outline Using pointer subscript notation Using pointer name and pointer/offset notation
Outline
Use array subscript notation to copy string in s2 to character array s1 Use pointer notation to copy string in s2 to character array in s1 Increment both pointers to point to next elements in corresponding arrays
Arrays of Pointers Arrays can contain pointers –Commonly used to store array of strings (string array) Array does not store strings, only pointers to strings Example –const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }; »Each element of suit points to a char * (string) suit array has fixed size ( 4 ), but strings can be of any size Commonly used with command-line arguments to function main
Graphical representation of the suit array.
Introduction of Object-Oriented Programming Integrated Time class case study Preprocessor wrapper Three types of “handles” on an object –Name of an object –Reference to an object –Pointer to an object Class functions
Preprocessor directive #ifndef determines whether a name is defined Preprocessor directive #define defines a name (e.g., TIME_H ) Preprocessor directive #endif marks the end of the code that should not be included multiple times
Software Engineering Observation Use #ifndef, #define and #endif to form a preprocessor wrapper that prevents header files from being included more than once in a program. Each element of a class should have private visibility unless it can be proven that the element needs public visibility. This is another example of the principle of least privilege.
Ensure that hour, minute and second values remain valid
Using setfill stream manipulator to specify a fill character
std::setfill Parameterized stream manipulator setfill –Specifies the fill character Which is displayed when an output field wider than the number of digits in the output value By default, fill characters appear to the left of the digits in the number –setfill is a “sticky” setting Applies for all subsequent values that are displayed in fields wider than the value being displayed
Declaration of Object Using class Time –Once class Time has been defined, it can be used in declarations Time sunset; Time arrayOfTimes[ 5 ]; Time &dinnerTime = sunset; Time *timePtr = &dinnerTime;
Performance Objects contain only data, so objects are much smaller than if they also contained member functions. The compiler creates one copy (only) of the member functions separate from all objects of the class. All objects of the class share this one copy. Each object, of course, needs its own copy of the class’s data, because the data can vary among the objects.
Accessing Class Members Dot member selection operator (. ) –Accesses the object’s members. –Used with an object’s name or with a reference to an object. Arrow member selection operator ( -> ) –Accesses members with a pointer to an object.. –Used with a pointer to an object.
Using the dot member selection operator with an object Using the dot member selection operator with a reference Using the arrow member selection operator with a pointer
Access Functions and Utility Functions Access functions –Can read or display data –Can test the truth or falsity of conditions Such functions are often called predicate functions For example, isEmpty function for a class capable of holding many objects Utility functions (also called helper functions) –private member functions that support the operation of the class’s public member functions –Not part of a class’s public interface Not intended to be used by clients of a class
Prototype for a private utility function
Calling a private utility function Definition of a private utility function
Constructors with Default Arguments Constructors can specify default arguments –Can initialize data members to a consistent state Even if no values are provided in a constructor call –Constructor that defaults all its arguments is also a default constructor Can be invoked with no arguments Maximum of one default constructor per class
Prototype of a constructor with default arguments
Parameters could receive the default values
Initializing Time objects using 0, 1, 2 and 3 arguments
Invalid values passed to constructor, so object t5 contains all default data
Destructors Destructor –A special member function –Name is the tilde character ( ~ ) followed by the class name, e.g., ~Time –Called implicitly when an object is destroyed For example, this occurs as an automatic object is destroyed when program execution leaves the scope in which that object was instantiated –Does not actually release the object’s memory
Destructors Destructor (Cont.) –Receives no parameters and returns no value May not specify a return type—not even void –A class may have only one destructor Destructor overloading is not allowed –If the programmer does not explicitly provide a destructor, the compiler creates an “empty” destructor