C++ Review for Test 2: List of Concepts Covered
Composition Relationship
- 'Has-a" relationship between objects
- an object of one type embedded as member data inside of an object of
another type
- Good for representing objects that are components of larger objects
- Also good for embedding objects into a "manager class", to manage
communication between components
- Class examples: Timer and Display example,
SodaMachine example
Enumerations:
-
a way to create new type with finite set of symbols as values
-
Format: enum typeName { list of value symbols };
-
Note: the value symbols are NOT strings
-
the value symbols are implemented as constant variables by computer
- Why?
- readability in source code.
- creation of a type with a limited number of possible values
- Enumeration as a function parameter type means validation probably
not needed on parameters (by the function)
- Caution: Do not try to use in direct cin or cout
statements (Remember, enum values are not strings!)
Arrays
Array Properties
- indexed collection of data elements of same type
- consecutive storage locations
- default indexing is 0 through size-1 (where
size is the number of elements in the array)
Declaring Arrays
- format: typeName variableName[size];
- The type can be any basic type or any user-defined type
- the size must be known by the compiler, so it must be a positive
integer literal or constant.
- 2-dimensional arrays
- Example: double table[5][10]
Initializing Arrays
- Can initialize arrays in the same line as declaration
- Format: type name[size] = { list of elements };
- Example: int list[5] = {1, 3, 5, 9, 10};
- The list of elements goes in { } and is separated by commas
- may leave size box empty when initializing on the declaration line
- compiler sets size.
- Can also initialize with for loops (good with regular patterns)
- Special case
- strings: null-terminated character arrays
- can initialize on the declaration with a string literal
- Example: char name[7] = "Marvin";
- size must leave room for null-character '\0'
Initializing Arrays of Objects
- with no initialization, default constructor used
- allowed to explicitly call constructors in the { }
- Example: Fraction nums[3] = { Fraction(2,3), Fraction(6),
Fraction() };
Using Arrays
- valid indices are 0 through size-1.
- may use any of these index numbers to access a single array element:
- may use any positive integer r-value to index arrays (i.e. variables,
expressions, etc)
- ** it is the programmer's job to check for out-of-bounds index!
- Copying Arrays
- Assignment between array names does not copy one array to another
- If you want to copy one array to another, do it element by
element (easy with a loop)
Using strings
- A string can be used like a normal array (of characters)
- cout and cin objects also work with strings (for output and input of words)
- >> operator for input stops at white space (space, tab, newline,
etc.)
- only good for one word at a time
Card game example and Array Techniques
- Array of Card objects embedded inside Deck class -- "has-a" relationship
- Array of Card objects embedded in Player class -- "has-a" relationship
- arrays of objects (and use of dot-operator)
- good to use tracking variables with arrays, to track usage
- especially good to use tracking variable when you have an array whose
allocated space is not always full! (see Player class and numCards
variable for example)
Pointers
Basics
- A pointer is a variable that stores an address
- declaration format: typeName * variableName;
- target -- the item that a pointer points to
- dereferncing the pointer (to get to the target)
- if p is a pointer, *p is the target (dereference the pointer with *)
Initializing pointers
If p is a pointer, then how can we fill in the blank?
p = _____
Essentially, four ways:
- NULL pointer
- pointer that stores address 0. Has no valid target.
- 0 is the only literal number that can be assigned to a pointer
- Another pointer of the same type
- a pointer is thought of as a "pointer to a" specific type
- different pointer types can NOT be assigned to each other (automatic
type conversions like on the basic types do not apply)
- An array name counts as a pointer (to whatever type the array is
built from)
- A string literal (e.g. "Hello") is an r-value
that counts as a (const char * )
- The "address of" an existing variable
- Using & on a variable means "address of" that variable.
- Note this is NOT the same as using & in a declaration (with a
type in front of it). That's a reference variable -- used in Pass
By Reference
- Example: &x means "address of x"
- May assign an address to a pointer (of matching type)
- a new operation (Dynamic Allocation -- See below)
Pointer Arithmetic:
- can subtract two pointers
- can add or subtract integers to or from pointers
- does not use literal integer. adds or subtracts that many units
of pointer type
- i.e. add x to a pointer-to-int actually adds (x * (size of an int))
Pointers and Arrays:
Pass by Address:
Pointers, Strings, I/O:
- strings are special cases -- null terminated character arrays
- Insertion operator can be used on name of char array to print the string
- stops printing at null character
- Extraction operator can be used on name of char array to read in string
- Stops at white space (space, tab, newline, etc)
- get and getline functions can be used to read up to a specific
delimiter
<cstring> library functions:
- strlen (string length)
- strcpy (string copy)
- strcmp (string compare)
- strcat (string concatenation)
- strncat, strncpy, strncmp
Dynamic Memory Allocation
Memory Allocation Categories
- Static -- compile time. size and types known in advance
- Dynamic -- run time. sizes and amounts can be set while program
running
Dynamic Allocation, Deallocation
- create dynamic space with the operator new.
- always use a TYPE after the word new.
- The new operator also returns the address of the allocated
space
- use a pointer to store this address
- can dynamically allocate basic variables, objects, and arrays
- can pass in parameters to constructors on dynamically allocated
objects
- deallocate dynamically allocated memory with operator
delete
- apply delete to the pointer, and it de-allocates the
target.
- Use delete [] for arrays
Notation:
- Arrow operator -- like the dot operator, but for pointers
- p->Show(); is the same as (*p).Show(); where p
is a pointer, *p is the object, and Show() is a member function.
Dynamically resizing an array (application example):
- dynamically create a new array of the needed size (need another
pointer for this)
- copy the data from the old array to the new one (use a for-loop)
- delete the old dynamic array (keyword delete)
- change the pointer so that the new array has the right name
Phonebook database example - examples of dynamic allocation,
dynamic resizing of array, pass by address, destructor
Some practice array algorithms to try (coding practice)
(You should be able to do these and other similar array algorithms)
- Compute and print the sum (product, average) of the elements of a
numerical array.
- A function that returns the maximum element of an array
- A function that prints all array elements that are between two given
values (parameters)
- A function that counts up all the even numbers in an array
- A function that computes the product of all positive numbers in an
array
- A function that adds all the odd numbers in an array
- A function that returns true if all elements in an array are
positive, and false otherwise