You are on page 1of 14

Enze Chen

Marty Stepp
CS 106B
Class Notes
Lecture 1 - 03/30/2015
Get Qt creator
Int main() {
Return 0 }
Lecture 2 - 04/01/2015
#include
<libraryname>: Use the C++ library:
libraryname.h : Uses the local directory library
Use <iostream> at beginning of program
<cmath> has common math functions
Using namespace std;
Allows for certain commands
Cout - console output
Use << to enclose what you want to print. Also use << to enclose
variables;
Endl - end line Better style than \n.
Cout << hi my age is << age << ok << endl;
Cin >> variable
Reads input from console and stores it in the given variable
Uses >> (!!!)
Often preceded by a prompt that explains to the user what it ask
s for.
#include simpio.h
getInteger(prompt)
getReal(prompt)
getLine(prompt)
Parameters send info into a method, return takes info out.
These libraries restrict what data types are allowed for paramet
ers
Comments: Use /* and */.
Functions: Saves some code, exits upon hitting return statement.
Type name(type name, parameters, etc...){
Statement;
Statement;
Return expression; //if return type is something other than voi
d
}
Call: name(parameters)
IMPORTANT: Order of declaration is very important.
Function prototype: Write heading of function at very top ( I prom
ise the function exists )
Heading is everything before {}. Put a semicolon after.
Value semantics: If primitive data types are passed, values are copied.
Reference Semantics: Attach a & after the data type, which links the inp
ut parameter to variable under nother method.
Can be used to write a swap function.
You can also pass the parameter as a data type
Benefits: Return more than one values, store the value directly
into the parameter.
Downsides: Hard to tell, slower than value, can't declare a lite
ral value.
Strings: #include <string>
string s = "hello"
s[k] or s.at(k) get the character at index k.

You can use + or += to concatenate strings.


Lecture 3 - 04/03/2015
Strings
You can concatenate
However, unlike Java, you can compare strings, using <, >, =
Unlike Java, you can also modify strings, such as with
str1.append(str2)
str1.erase(index, length)
No need to reassign(!)
//in Java, it's s = s + str2.
str.length()
str.find(str2) //finds a substring and returns index
However, if not found, it returns string::npos
**There are two types of strings.
C strings - char arrays. Inherited.
C++ strings (string objects), a new library in C++
"literals" are all old style
to avoid this, associate this with a string obje
ct str.
ie. string s (C++) = "hi there" (C) instead of "
hi there".
Or, you can use string("hi") + string("there")
Also, this doesn't work: int n = (int) "42"
//instead points
to the place in memory where "42" is and stores in n.
instead, use stringToInteger("42")
Neither does: string s = "hi" + '?'
or
string s = "hi" + 4
1
//memory address
Instead, string s = "hi"; // force the conversion to h
appen earlier
s += '?'
s += 41 //hi?) //this is because 41
is the ASCII code for )
cin can only grab one word at a time.
Use getline(cin, name) to grab whole phrase. //Uses a re
ference variable to the string.
I/O Stream
#include <fstream>
ifstream can read in from an input
Pattern: Open, Read, Close.
while(getline(input,line))
//keeps reading (boolean value) un
til no more lines exist
input.close()
If you are reading integers, then
string line;
getline(input, line); //get one line at a time
int n = strToInteger(line);
But if you don't have all integers,
if(stringIsInteger(line //boolean check to see if it i
s an integer
statements;
}
#include <filelib.h>
FileExists(name)
//boolean check to see if exists.
!For different OS, different directories exist so it's important
Grid - Our first data structure
Collections: Objects that we put data inside. "data structure"
There is the STL (Standard Template Lib) from C++ itself
.

We use Stanford C++ library that has nicer interface and


error messages.
This is a 2D indexed collection of elements
#include "grid.h"
Grid<type> name;
name.resize(r,c) //creates the actual size of board
name[r][c] = "string"
//C string auto converted
g.fill(value), g.inBounds(r,c), get, set, .toString()
Iterations
Row-major or Column-major
//whichever one is first
Pass by reference, to save memory and modifications(!)
Lecture 04 - 04/06/2015
Homeworks: Go to LAIR or YEAH Hours (led by SLs)
YEAH Hours are typically right after the assignments are release
d.
Section homework exercises: Do and put on paper.
Vector (Data Structure)
Why not arrays? - Not a lot of features, fixed sizes (and doesn'
t even know its own size!)
Also, you can go out of bounds, and it'll access memory
(without tell you)
Collections: Again, objects that stores data
Objects inside are called elements
We typically use collections, and later, we will see how
they're implemented.
#include "vector.h" It is basically like an ARRAYLIST from Java
Ability to compute size, add, remove, etc.
Default vector is empty.
We can use a for-each loop to get every vector element if just p
rint (and not modifying)
Remember: If we remove elements, we have to decrement. OR we loo
p in reverse.
Insertion involves a shift, so it takes more memory to move larg
er sections.
Linked List (Data Structure)
Similar in functionality to Vector
An ordered collection of elements, built out of many nodes, each
of which stores one value and links to another node.
However, it's harder to jump to any arbitrary index.
Abstract Data Types
Same implementation in two different ways.
Questions:
Can you use commas to separate the terms in the v.add() function.
Are there memory/style diff between for and for-each
Lecture 05 - 04/08/2015
stack - Only accessible element is the last added (top of the stack).
Implemented like an array.
Last in, first out. (LIFO)
push - Add an element to the top
pop - remove the top element.
peek - examine the top element.
Function calls are placed onto a stack(the stack frame)
Compilers use stacks to evaluate expressions
Matching up related pairs of things, like checking {} and () bal
ance.
Sophisticated algorithms like "backtracking" in a maze and "undo
" previous operations

#include "stack.h"
has stack.size() and stack.isEmpty()
stacks are printed horizontally
To find all elements in the stack....
DONT use for loop. Use while loop, then s.pop().
Be careful when passing by reference, because stack can get dest
royed.
queue - Only accessible element is the earliest added
Implemented like a linked list.
First in, first out (FIFO)
You can only add (enqueue) to the back
You can only examine/remove (peek/dequeue) from the front
Uses: operating system functions such as printing.
Helps to loop through with while(!queue.isEmpty()) as queue size
can change.
You can combine the two to reverse file contents.
Lecture 06 - 04/10/2015
Set: A collection of unique values.
Use: Counts the number of unique words in a large text file.
while (input >> word): Can grab all words in an input stream.
Allows for add, remove, search(contains), size, isEmpty
HashSet: Implemented using a special hash table
Very fast, but elements are stored unpredictably.
Set: Implemented using linked binary tree
Slower, but ordered list, in some way.
You can add, equate, intersect, differ sets.
for-each loop is a clean way to run over a Vector/Set
Map: A collection of PAIRS (key/value) in association with each other.
Linked so easy to find value given the key.
put(k,v) adds to the map
get(k)/remove(k) finds/removes value associated with the key.
The index (key) doesn't have to be an integer.
i.e. Map<string, int> name;
map[key] == value and map[key]++
Compound Collections: Collections of Collections
Vector<Set<int> > //include space to help compiler.
Use: We can find anagrams of a word in a dictionary.
Map<string, Set<string> >.
Lecture 07 - 04/13/2015
Recursion
Definition in terms of itself
Powerful when considering iterations
Some programming languages use exclusively recursion ('functiona
l programming')
Divide into base case and recursive case (think: "How is my prog
ram self-similar?")
Not too much slower than regular loops
Throwing exceptions
throw "expression" generates an error message
#include "error.h"
Lecture 08 - 04/15/2015
Moar recursion
Palindrome, binary, etc...
optional parameter (string word = "")
if not given, then it skips it no problem
Lecture 09 - 04/17/2015

Pay attention to order in nested recursion to see how it builds


may add pause(ms) to see it step by step
Algorithm Analysis
It's important to know differences between algorithms
efficiency: A measure of the use of computing resources by code
relative to run time, memory, etc.
Assume the following:
Any single line takes one time unit
a function's runtime is total number statements
a loop is just the looped number of statements
Growth rate: Changes in runtime as input size N changes
Big-Oh of N
Complexity class: A category of algorithm efficiency based on O(
N)
linear, constant, quadratic, logarithm, linear-log, expo
nential.
Example: Vector operations
add - constant
get - constant
insert - linear
remove - linear
set - constant
size - constant
toString - linear
Stacks and Queues are ALL CONSTANT runtime.
HashSet has const runtime for add, contains, and remove
Set has log(N) for those three operations.
Search:
sequential search is linear runtime
binary search: only for sorted data. Split into halves
Lecture 10 - 04/20/2015
Exhaustive search - Exploring every possible combination
Often done recursively
search(decisions)
if none are left, STOP
else, choose one, then recurse on all possible combos of
f that choice.
Helper functions
Useful in recursion if you need more parameters.
Simply returned in the original function.
In protoype, type out the default value, but in the heading, it
can be left out.
If something works and you don't know why, use cout to break it
down.
Dice rolls
We want to generate all possible sequences.
Using n loops is a depth-first search
Backtracking: Find solutions by trying partial solutions and the
n abandon not suitable ones
A brute force technique, often implemented recursively.
Lecture 11 - 04/22/2015
DiceSum: Very inefficient
For certain sums less than the dice number, it's pointless to ha
ve it loop through them all.
Lecture 12 - 04/24/2015
Backtracking: Choose, explore, unchoose
Change the type of output to get a different conclusion (bool vs void).

Can help stop the program early if you want one solution.
Classes: If you want to a data type to hold a new format (date, for exam
ple)
Class: Template for new objects. Create your own class or object
!
Abstraction hides the implementation of object from the user.
private instance variables, public constructors and methods.
C++: You need a .h (header) file and a .cpp file (implementation)
header: only interface and declaration of what you have in your
class.
#ifndef _name_h
#define _name_h (protection against multiple .cpp to in
clude this)
class Name {
public:
Name(param)
Type name(param)
Type name(param)
private:
type name
type name
};
//semicolon is really important!
private variables are very important (encapsulated) protects int
erface and integrity.
implementation: source file containing definitions.
Constructor creates the objects.
Date::name(param)
Add const after a header to inform that state does not change.
Every object will have a copy of the methods
Member functions, in other words, is encapsulated within
the object
Operator overloading
redefine the behavior of a common operator.
declare it in the .h file.
returnType operator <op>(parameters)
//yay, easy!
Lecture 13 - 04/27/2015
Operator overloading: Don't abuse
put operators towards the end of the header file.
const refers to whether it can change or not. (with overloaded o
ps)
Useful: To make it printable... //returns a reference to the str
eam so it can be chained.
ostream& operator <<(ostream& out, Type& name) {
statements;
return out;
}
friend can allow a public method to access private data.
Implementing a collection: Vector-like
First, arrays.
type* name = new type[];
referred to by Vector with a pointer.
type* name = new type[](); //initialized to have all e
lements zero.
memory must be free to avoid a MEMORY LEAK
delete[] name;
ArrayList: add(value), get(index), size(), remove(index), indexOf(value)
, toString();

Need: the array itself, size, capacity (refers to total spaces,


as arrays are static).
Create with initialized size and values.
Add/Insert: traverse backwards and pull values into an empty slo
t.
Can also implement private methods (such as check own size)
Lecture 14 - 04/29/2015
Back to ArrayList
destructor - opposite of a constructor. denoted by ~
called when the arraylist is destroyed.
destroyed? whenever a variable falls out of scope {}
helps free memory - or else it gets out of hand
Linked Lists
Each node object stores one element and a link to another node.
Pros: Fast to add/remove at any point.
Cons: Slow to access certain parts of the list.
Pointers
When variables are declared, they're stored in memory.
Memory addresses can be accessed with &var
Pointer: A variable that stores a memory address.
Declared with * after the type they point to.
Example:
int x = 42;
int* p = &x;
cout << p << endl; //0x7f8e20
cout << *p << endl; //42
*p = 99;
cout << x << endl; //99
If uninitialized, a pointer points to an arbitrary place in memo
ry.
NULL pointer: Memory address 0, intended to point to nothing.
If you store NULL, then it will crash if you try to foll
ow it.
You can make pointers point to an object.
to refer to members of the object, write pointer -> memb
er
The same as (*pointer).member
Dynamic allocation: constructing a pointer with new allows you t
o keep the object alive.
no destructor will be called when it reaches the end.
Structure: struct is similar to class, but has public member functions a
nd no functions.
ListNode: Stores an integer and an address that points to the ne
xt space.
Stores values using node# >data = value;
create a new pointer ListNode for each value.
now, link them all with node(i)->next = node(i+1).
Reassigning pointers: When you say a->next = b->next, the assigned place
is replaced, not the pointer.
Lecture 15 - 05/01/2015
Chain of nodes - what if this is really long?
traverse/print: Use a while loop until it points to null.
however, make sure that the nodes are still point to the correct
node.
Make a pointer copy ListNode* current = list;
while(current != NULL) {
cout << current->data << endl;
current = current->next;

}
LinkedList class
Implemented exactly like ArrayList and Vector
starts with a pointer called 'front'
to avoid falling off the edge, check (current->next != NULL)
one way to change is front = ____;
another is ____->next = ____;
get
Use a for loop to traverse current through indices
return current->data
insert
traverse i-1 nodes
create a temporary new node that points to the latter half, then
add it to the front.
if index passed is zero (front), create copy of old front and re
assign.
Lecture 16 - 05/04/2015
Freeing memory
new - stores a memory address that is preserved after function
Whenever there's a "new" we need a "delete" afterwards
put after individual constructors, or create a ~destructor to fr
ee all nodes.
Next assignment: PRIORITY QUEUE
Sometimes there's an urgency (printers with different access lev
els).
Provides fast access to highest priority element.
enqueue, dequeue, peek, peekPriority, isEmpty, size, toString, c
hangePriority, clear,
How to implement?
1) We can represent PQ as a Vector.
This however, has enqueue runtime of O(1), but d
equeue/peek runtime of O(N).
2) Maybe a sorted Vector?
Enqueue now has runtime of O(N), dequeue has run
time of O(N) due to remove and shift, but peek runs O(1).
3) Linked List
Value as a string, priority as an int.
Sorted: Dequeue/peek is now O(1), but
IMPLEMENT: Unsorted array, Sorted linked list, and Heap.
Heap: An arrangement of elements in an array.
start, or 'root' index is 1.
Every index has a "parent" index (i/2) and two "children" indice
s (i*2, i*2+1).
Add it at the first empty index, but then swap up until it is at
right index.
Adding has runtime of O(log(N)), peek has const runtime
remove: put last element into first, then bubble BACKWAR
DS (runtime O(log(N))).
Lecture 17 - 05/06/2015
Bogo sort: Shuffle until it's completely sorted. Average runtime = O(N!)
, worst case INFINITY
Quantum sort: Multiple parallel universes, runtime O(1).
Selection sort: Store a minIndex and scan through i,j to find minIndex a
s you go. Runtime O(N^2).
Insertion Sort: Take successive elements and group them into the previou
s sublists. Runtime O(N^2) but slightly faster than selection.
Merge Sort: Divide data in half, sort each half, and then combine sorted
halves. Recursively, runtime O(N logN).

When merging, compare front of both groups, and slide forward as


you compare successive elements in two groups. O(N).
Be sure not to walk off the edge of either group.
Splitting into two is log(N). Therefore total runtime is N*log(N
).
Looks a lot uglier, but sorts much faster.
Lecture 18 - 05/08/2015
Tree: A directed (one way), acyclic (no loops) structure with linked nod
es
Binary tree: A tree where each node has at most two children.
Top node is root. each node can have data, NULL, and L/R sub-tre
e
Used in: Folders/files, family genealogy, AI decision trees, com
pilers, cell phone word auto-completion
Terminology: node: an object containing a data value and L/R chi
ldren
leaf: a node that has no children
branch: any internal node; neither root nor leaf
sibling: nodes with common parent
TreeNode* node, similarly can have node->data, node->left, node>right
print: Use recursion! The tree is branched pointers.
printHelper(TreeNode* node){
if (node != NULL) {
cout << node->data << endl;
printHelper(node->left);
printHelper(node->right);
}
}
typically Tree methods call a helper, and then recurse on L/R
contains: Check if it is within the tree.
MUST have a return false (NULL) AND a return true base case (fou
nd!)
return contains(node->left, value) || contains(node->right, valu
e)
applies short-circuiting to stop return prematurely if f
ound.
printSideways: similar to print, but order becomes right, self, left.
Lecture 19 - 05/11/2015
More binary trees!
review: Binary trees require recursion and often a helper functi
on that takes in a root.
traversal: An examination of the elements of a tree.
Often a specific order (after all, it's one way): top, l
eft, right (or w/e is recursive).
pre-order: root, left, right
in-order: left, root, right
post-order: left, right, root.
Trick: Draw a tight path along the tree, and pre:left, i
n:bottom, post:right.
Binary search tree (BST): Each non empty node has left:less, right:great
er, and each subtree also a BST.greater
The less/greater applies to EVERYTHING coming off the branch.
Runtime: General case log(N), worst case N.
How to add: Use helper to add(node, value).
But you can't have just base case if(node==NULL) b/c the
n it's never attached.
Put & in the parameter section of node

Implementation: The constructor sets root = NULL.


Lecture 20 - 05/13/2015
Even MORE binary trees!
Add doesn't work if we only reassign node = new TreeNode(value)
!First, if(root == NULL) {root == new TreeNode(value)};
if(node->left == NULL) {
node->left = new TreeNode(value);
}
*this "arms-length" recursion works, but is repetitive.
Use TreeNode*& node to assign by reference (passing the real thi
ng/address/associate value).
Any modifications to the tree should be passed by reference to a pointer
.
getMin(): Use helper to
Remove -- This is HARD if order is to be maintained
Case 1: a leaf --> replace with NULL
Case 2: a node with a left child only --> replace with left chil
d
Case 3: a node with a right child only --> replace with right ch
ild
Case 4: a node with both children --> replace with min from righ
t OR max from left.
remove(TreeNode* node, int value){
First, WALK down the tree. then....
if(node == NULL)
else if (node->left == NULL && node->right == NULL)
trash = node
node = NULL;
else if (node->left == NULL)
trash = node
node = node->left;
else if (node->right == NULL)
trash = node
node = node->right;
else
int newData = getMin(node->right);
node->data = newData;
remove(node->right, newData);
finally, free up memory
delete trash;
Enqueue and dequeque - bubble the heap in a way like the tree
ASCII encoding - characters represented by int values with the same size
Huffman encoding - Use a binary tree to encode in different sizes
Lecture 21 - 05/15/2015
+3 points on midterm! - Now 45/45
Graphs! - A set of Vertices connected by Edges
degree - number of edges off of a vertex
Example: We can have the boggle board be V:letter cubes and E:ne
ighboring connections
Path - A sequence of edges from a to b. Length is number of V or
E (typically V; just be consistent).
Reachable: If path exists.
Connected: If all vertices are reachable (Graphs CAN BE disconne
cted)
Complete: All vertices connected to every other.
Cycle: A path that begins and ends at the same node.
Acyclic: One that does not contain any cycles.

Loop: An edge directly from a node to itself (Markov chain?)


Weighted graphs: Cost associated with a given edge,
Some have weighted edges, and some are unweighted. Generally not
negative
Directed graph (digraph): Edges are one-way between vertices.
Separated in/out degree. May not be connected anymore.
Can have A -> B AND B -> A, but they should be separated
and may have different weights.
BasicGraph: In the Stanford C++ Library. A DIRECTED graph library.
Vertex: Must be a string. Edge is a connecting line between V1 a
nd V2.
To make undirected graph, just add it twice from A->B then vice
versa
Stores structure of information as edge with pointers (they're d
irected after all)
Example: string coolest(string filename){
ifstream input;
input.open(filename);
string name1, name2;
BasicGraph graph;
while(input >> name1 >> name2){
graph.addVertex(name1);
graph.addVertex(name2);
graph.addEdge(name2, name1);
//now it's name1 is foll
owed by name2
}
cout << graph << endl;
//prints as all vertices first,
then all edges in alphabetical order.
for(Vertex* v : graph) {
cout << "vertex: " << v->name << endl;
int followers = 0;
for(Vertex* neighbor : graph.getNeighbors) {
followers += graph.getNeighbors(neighbor).size()
;
}
if (followers > max) {
max = followers;
maxName = v->name
}
}
Huffman Encoding (file compression algorithm)
bits - much smaller than what we're used to working with.
Make frequent chars have smaller bits, less frequent have larger ones.
EOF is a byte at the end with ASCII value 256
If PQ has more than one node, pull out two, then combine them.
Gets resorted. repeat.
Traverse tree to find full binary encoding of each character.
Put into a new map of characters to bits
PREFIX PROPERTY: No character's encoding is the prefix of another char.
Use same Huffman tree to decompress.
Bit I/O stream: ibitstream
int readBit()
//reads a single 1 or 0; returns -1 at end of f
ile.
obitstream: void writeBit(int bit) Writes a single bit (must be
0 or 1).
Lecture 22 - 05/18/2015
Depth-first search: Explore every path until you get to the end, in succ

ession.
Guarantees a find, should it exist, and returns first one.
Breadth-first search: Explore each level of connection among all possibl
e paths.
Will always find shortest possible path.
Word-Ladder!
In general, DFS uses less memory for storage than BFS. Runtime O(V + E).
Dijkstra's Algorithm: Finds the MIN WEIGHT path in a graph.
General: Create a table that keeps track of best path to a curre
nt vertex and updates.
Pseudocode: Initialize with every vertex at INFTY except V1, whi
ch is 0
Load into a PriorityQueue and dequeue ea
ch vertex to be visited.
if (V = Vn), done!
if (cost < n's cost) update cost;
Each vertex can also store a weight and a previous vertex.
Helps to backtrack once you reach the final destination.
Lecture 23 - 05/20/2015
More graphs!
Common bugs with Dijkstra's - Update the PQ! and make sure mark/unmark i
s done correctly
A* Search: Similar to Dijkstra's
heuristic: A speculation, estimation, or educated guess that gui
des the search.
example: On Google Maps, take the straight line distance
as estimate.
admissible: NEVER overestimate (or else things might blo
w up).
key difference: Run Dijkstra from a -> b, BUT add a heuristic fr
om b -> c as you run the algorithm.
pqueue := (vi, at priority H(vi, v2)).
!!!Make sure to compute cost separately when updating.
add heuristic only when updating priority on rec
ursive call
Lecture 24 - 05/22/2015
Spanning trees: A set of edges that connects all vertices with no cycles
.
Minimum spanning tree (MST): lowest combined edge weight (cost).
Kruskal's algorithm: Finds a MST in a given path (guaranteed)
Remove all edges from the graph.
Place all edges into a priority queue based on their weight
while (PQ is not empty)
Dequeue an edge from PQ
If edge's endpoints are NOT already connected, add to gr
aph (!!!This is kinda hard)
otherwise do nothing
Able to make mazes (remove walls until vertices and edges form M
ST)
When implementing....
cluster: group of vertices that are connected.
now just figure out if two vertices are in the same clus
ter
must be able to MERGE clusters.
Graph implementation
Vertex? edges? paths?
Method 1: edge list - an unordered list of all edges in the grap

h
Vertices are implicitly contained in the set of edges.
Fast for printing out all neighbors
Method 2: adjacency list - lists of each vertex's neighbors
Fast for finding all neighbors of a vertex.
Method 3: adjacency matrix - NxN matrix where the weight of each
edge is the a[i,j] entry.
row is start, column is the ending vertex.
Underlying representation is comprised of many Maps.
Lecture 25 - 05/27/2015
Hash Implementation
Set: Could be done with array or sorted array
Strange idea: What if we stored every value i at index i?
Well, other than memory/sparseness, it works pretty darn fast
Hash idea: Store any given element value at a specific index.
Hash function: Mapping process from index to values.
To improve our strange idea...group terms into buckets of mods.
buuuut...what if you add two values with same value % 10?
probing: resolve a collision by shifting it to another i
ndex.
separate chaining: create a list at each index storing a
ll values
rehash: When table is too full, just grow to a larger array
load factor: ratio of # elements / hash table length

Lecture 26 - 05/29/2015
INHERITANCE: A hierarchy of related classes.
One class EXTENDS another class, absorbing its data/behavior
Superclass: parent/base class where everything begins
Subclass: The class that extends from the superclass
Gets everything superclass have.
Example: The Trailblazer world classes.
Example of Inheritance: Create an "Employee.cpp" superclass.
Then extend into "Lawyer," "Programmer," etc...
Subclasses must inherit EVERYTHING.
However, methods can be overwritten in the subclass
"virtual" keyword must be declared in superclass -- might as wel
l make all methods virtual then! (no problem)
header in subclass is the same. Just different .cpp implementati
on.
To call superclass method, write "Superclass::method()" anywhere
.
Subclasses are still forbidden to directly access private variables of s
uperclasses.
Workarounds: Create a public "setField()" method
or subclass_Constructor(params) : superclass_Constructor
(params)
^initialization list
Superclasses can now implement methods that only belong to the subclass
Example: Lawyer can have a "sue" method.
Multiple Inheritance: One subclass has multiple superclasses
Example: iostream is a subclass of istream and ostream.
Private Inheritance: A subclass inherits a superclass but cannot tell ex
ternally
class Name : private SuperclassName
POLYMORPHISM: You can create a superclass object that belongs to a subcl
ass

Pointers: A pointer of type T can point to any subclass t.


However, a subclass specific method cannot be applied to the poi
nter
Instead, you must cast to (Subclass*)
You should NOT cast a pointer to something that it is not. Will
crash!
General test questions: Observe super/subclass, or write your own subcla
ss.
Could help to memory block diagram the class hierarchy.
1) Look at variable type and does it have the method?
If not, then you'll have a compiler error
2) Look at the object type and execute it from the object.
This applies to all public data fields, but private meth
ods/variables can't be accessed from superclass.
What about with a type cast?
1) Make sure the cast type has the method (rather than the class
type)
2) Then run the method from the object class.
Lecture 27 - 06/01/2015
template - A function or class that accepts a type parameter(s)
Allows you to write a function that can accept many types of dat
a.
template <typename T>
T bigger(T a, T b){
if(A>b){
return a;
} else {
return b;
}
}
template class: A class that accepts a type parameter(s)
in the header/cpp files, mark each class/function as tem
plated
Used in Vector, Set, ArrayList, etc...
Write on top of every method.
Class<T>::name(param)
Standard Template Library: Standard set of classes and algorithms for C+
+
Many types are the same (maybe with lowercase).
Lots of the underlying implementation is similar too
Error handling sucks
vector
Cannot print an entire vector
Able to access out of bounds
iterators: used in loops
Easily go through a data set
Lecture 28 - 06/03/2015

You might also like