CS 246 Notes
CS 246 Notes
CS 246 Notes
CS-246
Object-Oriented Programming
Table of Contents
IO redirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Wildcard Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
pipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Output as arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
egrep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
File Permission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Shell Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Shell scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Function Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
New Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Dynamic Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Return by value, pointer, or reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Preprocessor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Separate Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Include Guard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
C++ Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Default/Zero Parameter Ctors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Big 5 cont. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Arrays / const methods / invariants / encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Iterator Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Range-Based For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Finish Accessors/Mutators System Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
UML(Unified Modelling Language) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Inheritance, Virtual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Destructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Virtual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
C++ Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Observer Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Iterator Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Factory Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Template Method Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Public Virtual Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
2
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
+ intuitive/easy to learn
- inflexible
+ modules/flexible
- you get a command prompt where you type commands
- steep learning curve
> ls - listing of non-hidden files with formatted display (i.e. more spaces between names);
3
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
IO redirection
Wildcard Matching
> prog1 | prog2 => prog1 > temp and prog2 < temp
– ls *.txt => match any file end with .txt [Shell intercepts the Globbing Pattern, and substitutes the
globbing pattern with filename that matches]
> Linux pipe | connects stdout of prog1 to stdin of prog2
stdin stdout => stdin stdout + stderr
Start Program 1 Program 2 Stop
pipe
> prog1 2> err.log | prog2 2≫ err.log => Input redirection errors of two progs
Example.
Q: Count number of words in the first 20 lines in sample.txt
A: head -20 sample.txt | wc -w
Example.
Q: Suppose files words1.txt words2.txt etc. contain lists of words, 1 per line. Print a duplicate free list of
words in words*.txt
A: cat words*.txt | sort | uniq
4
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Output as arguments
> echo "Today is $(data) and I am $(whoami)" => Single argument (MUST double quote)
egrep
> egrep "cs246 | CS246" = egrep "(cs|CS)246" ≠ egrep "(c|C)(s|S)246 = egrep [cC][sS]246
> cs.*246 or .*cs.*246.* => output lines containing a substring cs followed by 0 or more chars followed by 246
> ls -a | egrep "^[^a]*a[^a]*$ => list all files in current directory whose name contains exactly one a
File Permission
5
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Shell Variables
> x=1 => all shell variables are strings (no spaces between)
> $PATH => a list of directory paths system used to search commands separated by :
Shell scripts
6
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
14 # Method 2
15 if [ $ ? - eq 0 ]; then
16 echo Not a good password
17 elif [ $ ? - ne 0 ]; then
18 echo Maybe a good password
> Linux process sets/returns a status code of last executed command (hidden as $?)
7
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
16 fi
17
18 x =1
19 while [ $x - le limit ]; do
20 echo $1
21 x = $ (( x + 1) )
22 done
> $((x + 1)) => treat x as arithmetic argument and do arithmetic operation instead of string concatenation
> Double quotes make a content to a single argumetn like a single stirng
8
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Chapter 02 - C++
Professor: Nomair Author: Yiming Dai
I/O
> When we use ‘using namespace std’, we cannot use our own defined ‘cout’
> Compile using g++ -std=c++14 hello.cc -o myprog (-o means executable)
> When we include iostream we are able to access 3 global variables
i. std::cout (struct ostream) => connects to stdout with output operators cout ≪ ⋯
ii. std::cerr (struct ostream) => connects to stderr with output operators cerr ≪ ⋯
iii. std::cin (struct istream) => connects to stdin with input operators cerr ≫ ⋯
> File: Plus.cc => Reads 2 ints and prints the result of addition
1 # include < iostream >
2 using namespace std ;
3
4 int main () {
5 int x , y ;
6 cin >> x >> y ;
7 cout << x + y << endl ;
8 }
> cin will read from the first non-whitespace char until it hits a whitespace
> When reading from input, it’s a good idea to check if a read successful
> If a read fails, the expression cin.fail() is going to be true
> If a read fails due to EOF, cin.fail() and cin.eof() are to be true
> File: io/readInts.cc => Read all ints from stdin and echo one per line to stdout. Stop if a read fails
1 # include < iostream >
2 using namespace std ;
3
4 int main () {
5 int i ;
6 while ( true ) {
7 cin >> i ;
8 if ( cin . fail () ) break ;
9 cout << i << endl ;
10 }
11 }
9
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
> C++ defines an automatic conversion from istream (type for cin) to bool;
> cin is treated as true if the last read succeeded, false otherwise;
> If a read fails, all subsequent reads fail * (unless you ackowledge the failure)
String
C C++
Comparison strcmp ==, !=, <, >
Length strlen str.length();
Concatenation strcat(s1, s2) s1 = s1 + s2;
Character Access s[i] s[i]
10
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
1 int x = 95;
2 cout << x; // prints x in decimal
3 cout << hex << x ; // prints x in hexadecimal
4 cout << dec ; // back to default print option
> EVerything we learnt about reading/writing from/to stdin/stdout applies to other sources of data.
> Anything you can do with istream variables (e.g. cin) you can do with an ifstream variables;
> Anything you can do with ostream variables (e.g. cout) you can do with an ofstream variables;
> The file is closed using ifstream when the variable goes out of scope (e.g. stack pop up)
Function Overloading
> In C++ we write functions of same name as long as the numbers or types of arguments have a difference
1 # Legal in C ++ but not in C
2 int neg ( int x ) { return -x ; }
3 bool neg ( bool b ) { return ! b ; }
4 # cin >> a is equivalent to operator >> ( cin , a ) [ a is pass by reference ]
> If multiple functions with the same name appears, ‘func()’ will not be compiled;
New Syntax
11
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
1 struct Node {
2 int data ;
3 struct Node * next ;
4 };
5 Node n = {5 , NULL };
6
7 # Constants
8 const int * p = & n ;
9 p = & x ; [ Legal ]
10 * p = 5; [ Illegal ]
11
12 int * q = & n ;
13 * q = 2; [ Legal ]
14
15 int y = 42;
16 p = &y;
17 * p = 5; [ Illegal ]
18
19 int * const r = & n ; # r is a constant pointer to integer
20 r = & y ; [ Illegal ]
21 * r = 1; [ Legal ]
22
23 int const * p = & n ; # p is a pointer to a constant integer
Reference
1 int y = 10;
2 int & z = y ;
3 # z is an lvalue reference to y ; it acts like a const . ptr . to y ;
4 # A lvalue reference is a const . ptr . with [ automatic dereference ];
5 # which means no need to write ‘* z =15 ’ but rather ‘z =15 ’
6
7 int * q = & z ;
8 # above create a ptr . to the integer
9 # z acts like y ( a alias to y )
10 # thus size ( z ) = size ( y )
11
12 # Cannot create a reference to a reference
13 # Cannot create a ptr . to a reference but can create a reference to a ptr .
14 # Cannot create an array of reference
15 # References must be initialized ;
16 # References must be initialized to something with an address
17 int & z = 5; [ Illegal ]
18
19 # Lvalue is (1) a storage location and (2) something with an address
20 # Lvalue = > anything that can be written on the LHS of an assignment
21 # Rvalue = > anything not an lvalue | temp / computed value
22 void inc ( int & x ) {
23 x = x + 1;
24 }
25 int y = 5;
26 inc ( y ) ;
27 cout << y ; = > print 6
28
12
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
29 std :: istream & operator >> ( std :: istream & in , int & x ) ;
30 # return type is std :: istream since may need consecutive reading
31 # cin >> x >> y
32 $ streams cannot be copied
33
34 struct ReallyBig {};
35 void f ( ReallyBig rb ) ;
36 ReallyBig b = ___ ;
37 f ( b ) = > requires create huge stack frame or pass by value of b
38
39 # C ++ could pass by ptr . to avoid copy and pass by reference by below
40 void g ( ReallyBig & rb ) ;
41 g ( b ) ; = > within g , rb is another name for b
42 # changes made by g will be cisible outside g
43
44 void h ( const ReallyBig & rb ) ; = > no copy | h cannot modify the original
45 # Pass by reference to const whenever possible for anything bigger than an Int
Dynamic Memory Allocation
13
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
3 Node n ; # being " copied " into " m " , but as of C ++11 , not actually this ↩
inefficient
4 return n ;
5 }
6 Node m = getNode () ;
7 # See more about move semantics versus copy semantics
8
9 # Better method below
10 Node * getNode () {
11 return new Node ; # Have to remember and free it
12 }
13 Node * ptr = getNode () ;
14 delete ptr ;
15 # If used ( Node &) same problem ; i . e . bound to variable that no longer exists
16
17 # Best way
18 Node & getNode () {
19 Node * ptr = new Node ;
20 return * ptr ;
21 }
22 Node & n = getNode () ;
23 delete & n ;
24
25 # Q : which to use ?
26 # A : return by value ; if can , since nto actually as expensive as it looks ( at least ↩
in C ++11 and up )
Operator Overloading
1 # I / O operators we have already seen use pass by ref . and return by ref .
2 cin . operator >> ( int )
3 std :: istream & operator >> ( std :: istream & in , int & i ) ;
4 std :: ostream & operator << ( std :: ostream & out , const int & i ) ;
5
6 std :: ostream & operator << ( std :: ostream & out , const Node * n ) {
7 if ( n != nullptr ) {
8 out << n - > value ;
9 }
10 return out ;
11 }
12 3 If not modifying the parameters , often want to return by value ;
Preprocessor
Tutorial
> ‘using std::string;‘ => only use string part, better to debug;
14
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Separate Compilation
– type definitions
– function declarations
– function defintions
> By default, the compiler compiles links and produces an executable file;
> To just compile g++ -c file.cc produces .o (object) files Object files contain
– compiled binary
– a list of things that were defined
– a list of things that were required
> Use a linker to merge object files g++ main.o a.o -o a.out
> Separate compilation allows us to only recompile files that have changed and then link everything
Include Guard
C++ Classes
1 // student . h
2 # ifndef STUDENT_H
3 # define STUDENT_H
4 struct Student {
5 int assns , mt , final ;
6 float grade () ;
7 }
8 # endif
9
10 // student . cc
11 # include " student . h "
12 float Student :: grade () { // scope resolution = > " In the scope of "
15
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
> In C++ all structs are allowed to have functions, so they are all classes;
> A function written inside a struct is called a members function => Method
> Calling a method requires an object of that class => within the method we have access to the fields of the
object on which we called the method
i. this == &billy
ii. ∗this == billy
> C++ allows to write methods to construct objects => constructors (ctors)
18 struct Student {
19 Student ( int assns , int mt , int final ) ; // no return value
20 // constructors have the same name as the class
21 }
22
23 Student :: Student ( int assns , int mt , int final ) {
24 this - > assns = assns ;
25 this - > mt = mt ;
26 this - > final = final ;
27 }
28
29 Student billy {80 , 50 , 70};
30
31 Student * pBilly = new Student {80 , 50 , 70};
32 delete pBilly ;
– sanity check
– can overload
– default value for parameters
1 struct Student {
2 Student ( int assns = 0 , int mt = 0 , int final = 0) ;
3 }
4
5 Student :: Student ( int assns , int mt , int final ) {
6 this - > assns = assns < 0 ? 0 : assns ;
7 this - > mt = mt < 0 ? 0 : mt ;
8 this - > final = final < 0 ? 0 < final ;
16
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
9 }
10
11 Student s1 {80 , 45}; // final = 0;
12 Student s2 {}; // all are 0
> Rule 1: If we write our own ctor, we lose the default ctor
1 struct Vec {
2 int x ;
3 int y ;
4 Vec ( int , int ) ; // two integer value default to 0
5 }
6 // Valid = > Vec v {1 , 2};
7 // Invalid = > Vec v ; // no default ctor
i. Space is allocated
ii. Field initialization: call default ctors for fields that are objects
iii. Ctors body runs
17
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
> The free copy ctor might not always do the correct thing
1 struct Node {
2 int data ;
3 Node * next ;
4 Node ( int , Node *) ;
5 Node ( const Node &;)
6 };
7
8 Node :: Node ( int data , Node * Next ) : data { data } , next { next }{}
9 Node :; Node ( const Node & others ) : data { others . data } , next { others . next }{}
10 Node * np = new Node {1 , new Node {2 , new Node {3 , nullptr }}};
18
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Big 5 cont.
> Destructors
1 Node * np = new Node {1 , new Node {2 , nullptr }};
19
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
> Sometimes the one we get free does not do the correct thing
1 Node n1 {} , n2 {} , n3 {};
2 n2 = n2 ; // n2 . operator = ( n1 ) ;
3
4 Node & Node :: operator =( const Node & others ) {
5 if ( this == & others ) return * this ; // 1.
6 data = others . data ;
7 delete next ; // 2.
8 next = others . next ? new Node {* others . next } : nullptr ;
9 return * this ; // return a reference
10 }
11
12 // 1. if new fails to allocate memory , next is not assigned ;
13 make next a dangling ptr ;
14 Self Assignment Check ;
15 Betles to delay deleting next until we know that new will not fail ;
16
17 // 2. next might already pointing to heap memory ;
18 n1 = n1 ; n1 . operator = ( n1 ) ;
19 // next and others . next are the same = > access a dangling ptr ;
20
21 // Optimized version below
22 Node & Node :: operator =( const Node & others ) {
23 if ( this == & others ) return * this ; // 1.
24 Node * temp = next ;
25 next = others . next ? new Node {* others . next } : nullptr ;
26 delete next ; // 2.
27 data = others . data ;
28 return * this ; // return a reference
29 }
20
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
22
23 // rvalue / node . c
24 // 2 calls to Basic ctor
25 // 2 calls to copy ctor ( to copy argument )
26 Node n2 { return value };
27 // 2 more calls of copy ctor ( construct n2 as copy of return value )
> Rule of 5: If you need to write a custom copy ctor, or copy operator=, or move ctor, or move operator=, then
you usually need write all;
> Copy/Move Elision => Under certian conditions, the compiler is allowed (not required) to avoid some
copy/move ctor calls(even if these have side effect)
1 Vec v = makeVec ()
2 // This would cause move / copy ctor to be called
3 // The compiler may directly construct the Vec in the space for Vec v
4
5 Void foo ( Vec v ) { };
6 foo ( makeVec () ) ;
7 // fno - elide - constructors
21
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
1 struct Vec {
2 int x , y ;
3 Vec ( int , int ) ;
4 }
5 // Want compile as default ctor gone
> Options:
1 // implement a default (0 param ctor )
2 // stack arrays : use C ’s array initializing syntax
3 Vec arr [2] = { Vec {1 ,2} , Vec {3 ,4}};
4 // Instead of array of objects , create array of pointers to object
5 Vec * arr [3];
6 Vec ** arr = new Vec *[3];
7 for ( ) {
8 delete arr [ i ];
9 }
10 delete [] arr ;
> const object can only call methods that are const
> Invariants => some assumption/statement that must not be violated for program to function corectly
22
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
10 Node n2 {3 , nullptr };
11 // When n2 is out of scope , dtor will run automatically
12 // Cannot call delete below
13 Node n1 {4 , & n2 };
> Encapsulation
23
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
18 delete next ;
19 }
20 }
21
22 List ::~ List () {
23 delete thelist ;
24 }
25
26 void List :: addToFront ( int n ) {
27 thelist = new Node (n , thelist ) ;
28 }
29
30 int List :: ith ( int i ) {
31 Node * curr = thelist
32 for ( int j = 0; j < i ; ++ j , curr = curr - > next ) ;
33 return curr - > data ;
34 }
> We will create a new (Iterator) class that acts as a ptr into a list
> To Do List
24
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
16 return * this ;
17 }
18 bool operator !=( const Iterator & other ) {
19 return curr != other . curr ;
20 }
21 };
22 Iterator begin () {
23 return Iterator { thelist };
24 }
25 Iterator end () {
26 return Iterator { nullptr }; x
27 }
28 // prev . List Methods
29 };
30
31 // Client Code
32 itn main ( void ) {
33 List l ;
34 l . addToFront (3) ;
35 l . addToFront (2) ;
36 l . addToFront (1) ;
37 for ( List :: Iterator it = l . begin () ; it != l . end () ; ++ it ) {
38 cout << * it << endl ; // print 1 ,2 ,3
39 * it += 1; // change to 2 ,3 ,4
40 }
41 }
> C++ has built-in support/syntax for the Iterator Design Pattern
1 auto x = y ; // define x to be the same type as y
2
3 for ( auto i : l) {
4 cout << i << endl ; // i is int ( by value )
5 }
6 for ( auto & i : l) {
7 i += 1; // i is int & ( ref . to data fields )
8 }
– MyClass has methods begin/end which return objects of a class, say Iter.
– Iter. must overload !=, *(unitary), ++(unitary prefix)
– To force clients to use begin/end, make Iterator ctor provide
– if we make it private, List::begin/List::end will lose access (private really implies no access)
– the Iterator class can declare List to be a friend
1 Class List {
2 ...
3 public :
4 Class Iterator {
25
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
5 Node * curr ;
6 explicit Iterator ( Node * n ) : curr { n } {}
7 friend class List ;
8 };
9 };
> Keep fields private and provide accessors(getters) and mutators(setters) public
> Suppose a class has private fields and no accessors/mutators - want to implement the I/O operators => as
standalone functions
1 Class Vec {
2 int x , y ;
3 ...
4 friend ostream & operator < <( ostream & , const Vec &) ;
5 }
26
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Inheritance, Virtual
> A desired class inherits all members from the base class
– space is allocated
– superclass part is constructed
– subclass fields constructed
– ctor body runs
27
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
> protected => if a member is "protected" it is accessible by the class and its subclasses
1 Class Book {
2 protected :
3 string title , author ;
4 int numPages ;
5 public :
6 Book ( string , string int ) ;
7 }
8
9 Class Comic : public Book {
10 string hero ;
11 public :
12 }
13
14 Class Text : public Book {
15 string topic ;
16 public :
17 }
18
19 void Text :: addAuthor ( string a ) {
20 author += a ; // OK as author is protected
21 }
22
23 int main () {
24 Text t = ...
25 t . author = X // no access !
26 }
> Advice
Method Overriding
> By default, compiler looks at the declared type of the ptr. to choose which method to run (static dispatch)
> We typically want the method to be chosen based on the type of object => use virtual keyword
> Virtual Method => the choice of method is based on the runtime type of the object (Dynamic Dispatch) but
more costly than static dispatch
> Polymorphism => the ability to accommodate multiple types within one abstraction
28
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Destructor
Virtual
i. If a class might have subclasses, make the dtor virtual in the base class
ii. If a class will never have a subclass, declare it as final
1 class X {
2 virtual ~ X () {...}
3 }
4 class Y : public X {
5 ~ Y () {...}
6 }
7 class Z final : public X {
8
9 }
1 class Student {
2 public :
3 virtual int fees () = 0; // Pure Virtual Method = > No implementation
4 }
i. it is incomplete
ii. it is an ABSTRACT class
29
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
i. organize subclasses
ii. members (fields/methods) that are common across all subclasses can be placed in the base class
iii. act as an interface
iv. Polymorphism
C++ Template
30
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
69 ~ List () ...
70 };
71 List < int > l1 ;
72 l1 . addToFront (1) ;
73 List < List < int > > l2 ;
74 l2 . addToFront ( l1 ) ;
– template class
– dynamic length arrays
∗ heap allocated
∗ automatically resize as needed
> Stack unwinding => when an exception occurs, the call stack is repeatedly popped until an appropriate catch
slack is found
Exception
31
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
ii. throw e; => throw the caught exception but might have sliced the original exception
iii. throw; throws original exception
Observer Pattern
Design Pattern
Iterator Pattern
32
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
19
20 }; // Set :: Iterator IS A AbsIter
21 }
> We can now implement code that operates using AbsIter and not being tied to a specific data structure
1 template < typename Fn >
2 void foreach ( AbsIter & start , AbsIter & end , Fn f ) {
3 while ( start != end ) {
4 f (* start ) ;
5 ++ start ;
6 }
7 }
8
9 List e ...
10 List :: Iterator i = e . begin () ;
11 foreach (i , e . end () , addTen ( i ) ) ;
Factory Pattern
> The factory method pattern is called the virtual constructor pattern
1 class Level {
2 public :
3 virtual Enemy * createEnemy () = 0;
4 };
5 class Normal : public Level {
6 public :
7 Enemy * createEnemy () override { // more turtles }
8 };
9 class Castle : public Level {
10 Enemy * createEnemy () override { // more bullets }
11 };
12
13 Player * p = ...
14 Level * l = ...
15 Enemy * e = ...
16 while (p - > notDead () ) {
17 // generate enemy should depend on level
18 e =l - > createEnemy () ; // factory of enemy
19 }
> Base class implements the template/skeleton and the subclass fills the blanks
> Base class allows overriding some virtual method but other non-virtual methods must remain unchanged
> Some methods in base class are virtual and some are non-virtual
1 class Turtle {
2 public :
3 void draw () {
33
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
4 drawHead () ;
5 drawShell () ;
6 drawFeet () ;
7 }
8 private :
9 void drawFeet () {}
10 void drawHead () {}
11 virtual void drawShell () = 0;
12 };
13
14 class RedTurtle : public Turtle {
15 void drawShell () override {}
16 }
> Contradictory!
> In a NUI
1 class Media {
2 public :
3 void play () {
4 copyrightCheck () ;
5 doPlay () ;
6 }
7 private :
8 virtual void doPlay () = 0;
9 }
> In C++, dynamic dispatch does not account for runtime type of parameters
1 class Enemy {
2 public :
3 virtual void strike ( Weapon &) = 0;
4 };
5 class Turtle : public Enemy {
6 public :
7 void strike ( Weapon & w ) override { w . useOn (* this ) ;} // Compile time this ↩
becomes Turtle
8 };
9 class Bullet : public Enemy {
34
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
10 public :
11 void strike ( Weapon & w ) override { w . useOn (* this ) ;} // Compile time this ↩
becomes Bullet
12 };
13 class Weapon {
14 virtual void useOn ( Turtle &) = 0;
15 virtual void useOn ( Bullet &) = 0;
16 };
Book Hierarchy
> What if the behaviour does not really nelong to the classes?
STL std::map
35
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
Compilation Dependencies
i. avoid cycles
ii. fewer recompilation
iii. faster compile time
> Usage
– include a file when constructing another class since need to know its size
1 # include " a . h "
2 class C {
3 A a;
4 };
36
©
Fall 2019 CS-246 Object-Oriented Programming Yiming Dai
1 // . h
2 class A ;
3 class D {
4 A * pA ;
5 };
6
7 // . cc
8 # include " a . h "
9 pa - > method () ;
– Forward declaration with constructing methods but include a file in .cc file
1 // . h
2 class A ;
3 class E {
4 A foo ( A a ) ;
5 };
6
7 // . cc
8 # include " a . h "
9 A E :: foo ( A a ) {}
Reduce Dependencies
37