CS 246 - Object Oriented Software Development | Fall 2020

Linux File Permissions

Permission information: d rwx r-x ---

chgrp - change group

Changes group-name associated with a file

Usage: chgrp [-R] group-name file/directory-list

chmod - change permissions

Changes permissions of a file

Usage: chmod [-R] mode-list file/directory-list

Example: chmod go-rw foo, chmod a+r schedule.html, chmod g=rw test.txt

Note: if you chmod using binary numbers you can switch the permissions based on the binary representation of each of those bits

The File System

path: is the general name of a file or directory in textual format

Note: directories in linux are just a specialized form of file

Absolute and relative paths

/ is the root directory

. is the current directory, .. is the previous directory

Changing the current directory

cd to change directory
pwd to display path of working directory

The home directory

Each new user is given their own home directory

when writing a pathname, the shell replaces the special character ~ with the absolute path of your home directory.

The $PATH variable

When the name of a file is given without a path then the shell looks in locations defined global system variable named $PATH
The contents of the $PATH variable are a list of pathnames separated by the colon character (:)

$ echo $PATH /home/bob/bin:/user/local/bin:/usr/bin

you can run a program by giving its path to the shell

you can add to the $PATH variable by (this doesn't affect existing PATH values):

export PATH=$PATH:/location/program

The shell

A shell is a program that runs and gives an interface to communicate with the opreating system

In most linux distributions, a program called bash acts as the shell

SSH (Secure SHell) connection allows us to user the shell on another computer through the internet.

Standard input: stdin is a device where from the shell is reading text input
Standard output: stdout is a device where the shell is writing text output
Standard error: stderr is a device where the shell writes error messages to

The command ls

The command ls -l displays a long form of the list with the following information:

Executing commands

bash can run in an interactive (user provides commands) or non-interactive mode (a script file)

The command prompt

command prompt is what the shell displays in interactive mode when it is waiting for user input

Types of commands

Scripts: are text files that contain commands in a specific programming language.

Programs: are files that contain commands in binary format. They can be understood the operating system not by a human
and can be run without an interpreter

Input/Output redirection

The command cat

cat simple reads the contents of standard input and writes it back to standard output

Redirecting input and output

you can use the shell's redirect cat's standard input and output devices to read from or write to fiels.

cat < file1.txt

you can also redirect the standard output using >
cat > file2.txt

you can combined both redirections.

cat < file1.txt > file2.txt

you can redirect the standard error device with 2>. For example:

cat < file1.txt > file2.txt 2> log.txt

Commans-line arguments

Passing command-line arguments

you can pass arguments to a program or script by writing each argument separated by a space after the command name:

cat -n file1.txt

Difference between arguments and input redirection

cat -n < file1.txt essentially dose the same thing as cat -n file1.txt but they are different

the program echo reads each command-line argument to stdout

$ echo a file1.txt a file1.txt $ echo a < file1.txt a $

Quoting arguments

Spaces are treated as separators between arguments. If you want to pass an argument that contains spaces you need to quote it.
' single quotes will not interpolate anything. " duoble quotes will interpolate.

$ echo "My shell is $0" My shell is -bash $ echo 'My shell is $0' My shell is $0

Pipes

pipes allow us to use the output of one program as the input of another by connecting the second program's stdin to the first's stdout

We can combine these two programs by piping them. A pipe is made using the the character |

head -20 file.txt | wc - w
cat file.txt | head -20 | wc -w > words.txt

Note: echo changes whitespace of a file, do not combine echo with cat if u need to preserve the original file format

Globbing patterns

The shell can automaticall expand a few wildcard patterns to match all the files that satisfy the pattern.

cat *.txt

The following operators can be used in globbing patterns

Regular Expressions

Introduction to pattern matching

We will use the tool egrep which looks for lines that match a pattern.

$ egrep "CS246" < tasks.txt CS246: Assignment 2 anth221: Discuss conflict with CS246
$ egrep "(CS246|cs246)" < tasks.txt CS246: Assignment 2 cs246 : Exam 1 anth221: Discuss conflict with CS246

The syntax (x|y) matches to either the pattern x or y

$ egrep "(CS|cs)246" < tasks.txt CS246: Assignment 2 cs246 : Exam 1 anth221: Discuss conflict with CS246

egrep also has argument -i which ignores case

^ means "beginning of line" in regular expressions

$ egrep "^(CS|cs)246:" < tasks.txt CS246: Assignment 2

Advanced patterns

It is common to want to match to a pattern or nothing, the sorthand is ?

$ egrep "^(CS|cs)246 ?:" < tasks.txt CS246: Assignment 2 cs246 : Exam 1
$ egrep "^(CS|cs)246 *:" < tasks.txt CS246: Assignment 2 cs246 : Exam 1
$ egrep "^(CS|cs)246 +:" < tasks.txt cs246 : Exam 1

Pattern reference

Here's an example

$ egrep "^(CS|cs)2[0-9][0-9] *:.*[Aa]ssignment" < tasks.txt CS241: Finish assignment 1 CS246: Assignment 2

bash, egrep, and quotation marks

Since we just started with bash it is recommended to using ' single quotes around egrep patterns to avoid bash substitutions

$ echo "\hi" \hi $ echo "\\" \ $ echo "\\hi" \hi $ echo "$PATH" /usr/bin:/bin $ echo "\$PATH" $PATH

In comparison to:

$ echo '\hi' \hi $ echo '\\' \\ $ echo '\\hi' \\hi $ echo '$PATH' $PATH $ echo '\$PATH' \$PATH

Bash Scripts

Introduction

Creating a script file

It is convention, but not necessary, to use .sh for bash script files

#!/bin/bash date whoami pwd

we can run the program by telling bash to execute it basic basic.sh

Running a script file

The general rules for setting up a script file are:

  1. insert a shebang line as your first line
  2. always add user-level execute permission

Bash as a programming language

adding -x will make the script show every command and its arguments as it executes

Variables

Good list of potential problems here

Variable naming should follow similar naming conventions to C variable names.

When assigning veriables there should never be a $, a $ is only used to retrives values from a variable.

x=1 echo $x

it is good idea to user curly braces {} around variable names when retrieving their value ${x}

there are a lot of global variables available to you. - use the env command to see many of them

Special shell variables

#!/bin/bash egrep "^$1$" /usr/share/dict/words

Selection statements

if statement general structure must follow one of the two following forms:

if condition1 ; then statement1 statement2 elif condition2 ; then statement3 ... else statement4 statement5 fi

or

if condition1 then statement1 statement2 elif condition2 then statement3 ... else statement4 statement5 fi

specifying conditions

a conditions is generally specified with [ ] a pair of open square brackets. There must be a black space between the opening square bracked and the closing square bracket

if [ -e foo.txt ]; then cat foo.txt fi
if [ $foo -eq 2 ]; then echo equals 2 else echo not equal 2 fi

if you want to combine conditions using "and" or "or" use the keywords -a or -o.

Functions

functions can only return a positive integer value, 0 to 255, so we don't need to specify a return-type

foo() { echo "name is: " ${0} echo "foo argument 1 is: " ${1} echo "foo argument 2 is: " ${2} echo "foo argument 3 is: " ${3} if [ ${1} = "cat" ]; then return 0 fi return 1 }

and foo is called by saying:

foo ${3} ${2} ${1} echo 'foo returned ${?}' ${?}

Loops

bash provied two main types of loops, a counted loop and a loop that iterates over a list of items

here the general forms of a counted loop:

while [ cond ]; do ... done until [ cond ]; do ... done for (( expr1; expr2; expr3 )) ; do ... done

and here are examples of the forms:

x=1 while [ ${x} -le 5 ]; do echo ${x} x=$((x + 1)) done x=1 until [ ${x} -gt 5 ]; do echo ${x} x=$((x + 1)) done for (( x=1; x <= 5; x++ )) ; do echo ${x} done

here is a list iteration loop:

for variable in list; do command1 command2 ... done

Software testing

software can be tested manually by a human or automatically by a machine

In automated testing test suites are implemented that automatically test the software and compare results with expected ones.

Types of software tests

Unit tests

Integration tests

Functional tests (system tests)

Acceptance tests

Regressions tests

Performance tests

White/Black box tests

White box tests:

Black-box tests:

Grey-box tests:

Creating black-box test:

creating white-box tests

Introduction to C++

C++ allows for high-level abstraction as well as machine level work (backwards compatability with C)

C++ Standard refers to a particular standard, e.g. C++11 refers to the C++ 2011 standard.

Basics

#include <iostream> int main() { std::cout << "Hello world!" << std::endl; return 0; }

main must have a return value in C++ (0 for success, anthing else for error just like bash), if you don't add return 0 the compiler will add it for you.

There are ways around not writing std:: each time,

// solution 1 using std::count; using std::endl; // solution 2 using namespace std;

C++ file end in one of .cc, .cpp or .C

Compilation

You cannot just run C++ files, you must first compile them.
Compilers take high-level languages and produce machine-readable code by first preprocessing, then compiling, assembling, and linking.

We will use the GCC compiler, g++ is a "front-end" to gcc that specifies we're programming in C++.

Compiling: g++ hello.cc creates a.out by default
g++ -std=c++14 hello.cc specifies we want to use the C++14 standard (at a minimum)
g++14 hello.cc -o hello specifies the compiled name to have name hello (g++14 is an alias we created to shorten g++ std=c++14)

There are more options for the compiler which are useful

It is strongly recommended to learn a tool such as gdb for debugging

Input and output

There are three golbal variables in the standard (std) namespace whcih define stream objects used for basic input and output

The standard input stream object cin has several bits to track if an error has occured, we can only access these bits through methods fail() or eof()

if (cin.fail()) { ... } if (cin.eof()) { ... }

Error Handling

We see that the program will just silently fail if a user enters an invalid input for an integer.

Version 2:

#include <iostream> using namespace std; int main() { int i; while (1) { cin >> i; if (!cin) break; cout << i << endl; } }

Version 3:

the signature of the function operator>> that reads in an integer is:

std::istream * operator>>( std::istream & in, int & value ); ```C++ #include <iostream> using namespace std; int main() { int i; while (1) { if (!(cin >> i)) break; cout << i << endl; } }

Version 4: This will take advantage of C++11 where std::istream can be implicitly converted (we say it is coerced) to a Boolean type.

#include <iostream> using namespace std; int main() { int i; while ( cin >> i ) { cout << i << endl; } }

Version 5:
we will now modify the program so that it skips reading any non-integer value

  1. clear the fail bit after an error with cin.clear()
  2. we have to "throw away" the offending input with cin.ignore()
#include <iostream> using namespace std; int main() { int i; while (true) { if ( !(cin >> i) ) { // remember, operator! === fail() if ( cin.eof() ) break; cin.clear(); cin.ignore(); } else { cout << i << endl; } } }

File I/O

Reading from a file is almost indentical to reading from standard input. Instead of including the iostream library we include the fstream library and use the ifstream type.
writing to a file is similar except that we use the ofstream type

#include <fstream> int main() { std::ifstream infile{ "input.txt" }; std::ofstream outfile{ "output.txt" }; int i; while ( true ) { infile >> i; if (infile.fail() ) break; outfile << i << std::endl; } }

if input file cannot be opened for input

if output file doesn't exist

if output file doesn't have write permissions

The files will automatically close for us when the objects go "out of scope" and are destroyed on the final closing brace } of the program.

Formatting output

We will rarely require formatting beyond white space in this course, but it's good to know.

#include <iostream> #include <iomanip> using namespace std; int main() { for (int i = 0; i < 20; ++i) { cout << dec << setw(3) << i << oct << setw(3) << i << hex << setw(3) << i << endl; } }
#include <iostream> #include <iomanip> using namespace std; int main () { int i = 95; cout << hex << i << endl; cout << i << endl; float price = 2.00; cout << fixed << showpoint << setprecision(2) << price << endl; } $ g++14 manip.cc $ ./a.out 5f 5f 2.00

Strings

C C++
array of character: char * or char [] *type is std::string and requires inclusiong of <string> library
memory needs to be explicitly managed. Need to shrink and grow array explicitly manages memory for you
Easy to accidently overwrite '\0' and corrupt memory safer to manipulate
char * s = "hello"; char name [10] = "Jane\0"; std:: string s = "hello"; string name{ "Jane" };

Operations

these are a few of the common string oeprations/operators

Input/Output

String streams

There is stringstream type which is a hybrid of a string class and I/O stream class. It lets you read/write to/from strings using stream operators.

Input string streams

The primary purpose of an input string stream is to take an existing string and split it into separate words.

#include <iostream> #include <sstream> #include <string> using namespace std; int main () { string s; string s1{ "The quick brown fox\njumped over the lazy\t dog." }; istringstream ss1{ s1 }; while ( ss1 >> s ) { cout << s << endl; } string s2{ "Smith,Jane,99999999,Yu,Yaoliang,99999998" }; istringstream ss2{ s2 }; cout << "***" << endl; while ( getline( ss2, s, ',' ) ) { cout << s << endl; } }

Output string streams

There is almost no reason to use an output string stream object in this course (CS246)

#include <iostream> #include <string> #include <sstream> using namespace std; int main () { ostringstream ss; int lo {1}, hi {100}; ss << "Enter a # between " << lo << " and " << hi; string s {ss.str()}; cout << s << endl; }

Command-line arguments

Command-line arguments in C++ are the same as in C: The main function may take two arguments, argc and argv

#include <iostream> int main(int argc, char **argv) { for (int argi = 0; argi < argc; argi++) { std::cout << argv[argi] << std::endl; } }

Functions

functions in C++ are very similar to C. Basic format:

return-type function-name( type1 arg1, type2 arg2, ... ) { ... return value of appropriate type; }

Forward declarations

You should already know to separate a function into its declaration (signature) and its definition (implementation)

You must call functions only after they have been declared but you can define them wherever.

Overloading

C++ allows for functions to be **overloaded&& which means more than one function can have the exact same name so long as the number of arguments and/or their types is different.

Note: the decision as to which function must be called must be made at compile-time

The compiler does not distinguish between overloaded functions based on return types

Default parameters

Sometimes you want a function to behave the a way most of the time unless specified otherwise through a parameter.
We can do this with overloading, but then we'd have to maintain two functions, instead we use default parameters.

function declaration:

void processInput( bool log = false );

Note: All parameters with default values must come after those without.

Structures

C:

typedef struct Node_t { int value; struct Node_t * next; } Node; Node * head = NULL; Node n; n.value = 5; n.next = NULL;

C++:

struct Node { int value; Node * next; }; Node * head = nullptr; Node n{ 5, nullptr }, n1 = { 6, head };

Here is an incorrect example:

struct Node { int value; Node next; };

Constants

We can define immutable values with teh const keyword. A common convention is to name cosntant values using all capital letters:

const int MAX_GRADE = 100; const double MATH_PI = 3.14159;

you can also declare more complext types as constant such as a struct

Parameter passing

If we want to write a function that increments a value without having to assign its return value we need to pass the variables adress and directly modify it.
Normally we are only passing the value of a variable and any modification within the function does not affect it, this is called call-by-value

void inc( int * n ) { ++*n; } // same as *n = *n + 1; ... inc( &value );

References

References are a very important topic you should understand them well.

Let's introduce the concept of rvalues and lvalues (left and right)

for example :

int x = 5; int * ptr = nullptr;

A reference is an lvalue that acts like a constant pointer but the compiler automatically dereferences it. Since it's constant it must be initialized when it is defined.

int x = 5; int &y = x; int * ptr = &y; y += 2; *ptr += 3; std::cout << x << std::endl;

There are a number of things that cannot be done with an lvalue reference

  1. cannot leave them uninitialized int &x; is illegal, must be initialized with an lvalue
  2. cannot create a pointer to a reference int &*x; is illegal
  3. cannot create a reference to a reference int &&x; does not mean "reference to reference" we will see what it actually means later
  4. cannot create an array of reference int $refAarray[3] = {x, y, z}

let us revise the increment program:

#include <iostream> using namespace std; void inc(int &n) { n = n + 1; } int main () { int x {5}; inc(x); cout << x << endl; }

passing by value requires "copying" the value into the function which can be expensive for large data, so to incerase efficiency we can pass a constant reference which will allow us to read the data but not mutate it.

Advice: pass by const ref over pass by value for anything larger than an integer unless the function needs to make a copy anyways.

Warning: if you want to pass a literal integer it must be defined as a constant reference.

f(5) would not work with int f( int & n ) { ... }

f(5) works with int f( const int & n ) { ... }

Dynamic memory allocation

C C++
uses a library cstdlib now known as stdio.h that provides malloc,calloc,realloc and free. Only works with type (void*) so not type safe uses keywords new and delete. Type safe, i.e. allocates space appropriate of size and return a pointer of the appropriate type
#include <iostream> struct Node { int data; Node * next; }; int main() { Node n{ 5, nullptr }; Node * np = new Node{ 3, &n }; std::cout << n.data << ' ' << np->data << std::endl; delete np; }

Warning: if you fail to delete dynamically allocated memory you have a memory leak. It is considered incorrect in this course since it will eventually fail.

Dynamic array allocation

Node * nodeArray = new Node[10]; ... nodeArray[0].data = 5; nodeArray[0].next = nullptr; ... delete [] nodeArray;

Pointers and optional files

./test [ input-file-name [output-file-name] ] it is unix convention to specify (in documentation) optional arguments by enclosing them in []

it is common to have programs default to stdin or use files if supplied in arguments.

Here is a good example of how to handle this:

#include <iostream> #include <fstream> #include <string> void usage( char * pgmname ) { std::cerr << pgmname << " [ input-file-name [output-file-name] ]" << std::endl; } // usage int main( int argc, char * argv[] ) { std::istream * infile = &std::cin; std::ostream * outfile = &std::cout; if ( argc > 3 || argc < 1 ) { usage( argv[0] ); return 1; } // if switch( argc ) { case 3: outfile = new std::ofstream{ argv[2] }; if ( outfile == nullptr || outfile->fail() ) { delete outfile; std::cerr << "ERROR: unable to open output file \"" << argv[2] << '"' << std::endl; return 1; } // if // fall through to open up the input file next case 2: infile = new std::ifstream{ argv[1] }; if ( infile == nullptr || infile->fail() ) { if ( outfile != &std::cout ) delete outfile; delete infile; std::cerr << "ERROR: unable to open input file \"" << argv[1] << '"' << std::endl; return 1; } // if break; default: // do nothing break; } // switch // Echoes the input to output. std::string line; while ( std::getline( *infile, line ) ) { *outfile << line << std::endl; } // while // Closes the I/O files. Don't delete if standard input or output, though. if ( infile != &std::cin ) delete infile; if ( outfile != &std::cout ) delete outfile; } // main

Returning information

There are three ways a function can return values;

  1. return by value
  2. return by pointer
  3. return by reference

let's see examples of the three using the structure:

struct Node { int data; Node * next; };

Return by value

Node getMeANode( int value ) { Node n{ value, nullptr }; return n; }

Return by pointer

// THIS CODE IS INCORRECT Node * getMeANode( int value ) { Node n{ value, nullptr }; return &n; }
Node * getMeANode( int value ) { Node *nptr = new Node{ value, nullptr }; return nptr; }

Return by reference

Node & getMeANode( int value ) { Node *nptr = new Node{ value, nullptr }; return *nptr; }
Node & newNode = getMeANode( 5 ); ... // do something with newNode ... delete &newNode;

Which technique should we use

Operator overloading

we can also overload operators such as +,-,*,/, etc. in C++.

struct Vec { int x, y; }; Vec operator+( const Vec & v1, const Vec & v2 ) { Vec v{ v1.x + v2.x, v1.y + v2.y }; return v; } int main() { Vec v1{3, 4}, v2{6, 7}; Vec v3 = v1 + v2; }

We can multiply a vector by an integer

Vec operator*( const Vec & v, const int k ) { return { k*v.x, k*v.y }; } Vec operator*( const Vec & v, const int k ) { return k * v; }

Overloading << and >>

struct Grade { int theGrade; };

We want the output operator the print the value then a '%' sign

std::ostream & operator<<( std::ostream & out, const Grade & g ) { out << g.theGrade << '%'; return out; }

Rules for output operator:

  1. the return type is always std::osteram &
  2. the function name is always operator<<
  3. the first parameter is always the output stream std::ostream &
  4. the second parameter is always the information being output
  5. write the return statement to return whatever the name of the output stream is
std::istream & operator>>( std::istream & in, Grade & g ) { in >> g.theGrade; if ( g.theGrade < 0 ) g.theGrade = 0; else if ( g.theGrade > 100 ) g.theGrade = 100; return in; }

Rules for input operator:

  1. the return operator is always std::istream &
  2. the function operator is always operator>>
  3. the firs parameter is always the input stream std::istream &
  4. the second parameter is always the information being read in.
  5. write the return statement to return whatever the name of the input stream

templates:

std::ostream & operator<<( std::ostream & out, const typeToPrint & value ) { out << v ; // whatever is appropriate for the type you are outputting return out; } std::istream & operator>>( std::istream & in, typeToRead & value ) { in >> v ; // whatever is appropriate for the type you are reading in return in; }

Preprocessing and Compilation

The preprocessor

The C preprocessor is tasked with handling preprocessor directives, it's primary purpose is to control what code is included in your program.

the -E flag with g++ will make the preprocessor output to standard out

the preprocessor can also define constants #define GEESE 15 however in modern C++ and C this is unneeded and you should use const definitions since they are more type-safe.

the #if (ends with #endif) controls whether code is included (controlled by preprocessor).
Here is an example of debugging using #if

$ cat debug.cc #include <iostream> using namespace std; #define DEBUG_LEVEL 1 int main() { #if DEBUG_LEVEL >= 1 cout << "main has started" << endl; #endif cout << "Hello, world!" << endl; #if DEBUG_LEVEL >= 2 cout << "About to end main" << endl; #endif return 0; }

#ifdef and #ifndef check if a preprocessor variable is set:

[...] #ifdef DEBUG cout << "Debugging activated (I don't care what level)" << endl; #endif

#if 0 can be used to comment out large amounts of code since it nests properly unlike comments

preprocessor variables can be given in the command line to g++, e.g. $ g++ -std=c++14 debug.cc -DDEBUG_LEVEL=2 -o debug

Separate compilation

We split our code into two components:

The real power in separating our implementations is by having separate compilation this is useful for very large projects where compiling the entire project for one change would take a very long time.

$ g++ -c main.cc $ g++ -c vec.cc $ g++ main.o vec.o -o vecs $

if we only change something in main we don't have to recompile the entire project:

[... change main.cc ...] $ g++ -c main.cc $ g++ main.o vec.o -o vecs $

header files can only have declarations so we need to declare a variable in the header file with extern type name then define the varaible in an implementation file.

Make and makefiles

there is a tool to automate linking, make
a simple makefile for our previous example program is

vecs: main.o vec.o g++ main.o vec.o -o vecs main.o: main.cc vec.h g++ -std=c++14 -c main.cc vec.o: vec.cc vec.h g++ -std=c++14 -c vec.cc

note: the commands to create a target must be indented with tabs, even if you normally use spaces

the command to create any given target is called a recipe

to use the make file we only need to use the command make

$ make g++ -std=c++14 -c main.cc g++ -std=c++14 -c vec.cc g++ main.o vec.o -o vecs $

we can clean up unwanted side effects of building through a phony target (a target that only exists for its recipe and doesn't actually build anything)

$ cat Makefile vecs: main.o vec.o g++ main.o vec.o -o vecs main.o: main.cc vec.h g++ -std=c++14 -c main.cc vec.o: vec.cc vec.h g++ -std=c++14 -c vec.cc .PHONY: clean clean: rm *.o vecs $ make clean rm *.o vecs $

we can reduce clutter in our Makefile by using make variables

$ cat Makefile CXX=g++ CXXFLAGS=-std=c++14 OBJECTS=main.o vec.o EXEC=vecs ${EXEC}: ${OBJECTS} ${CXX} ${OBJECTS} -o ${EXEC} main.o: main.cc vec.h vec.o: vec.cc vec.h .PHONY: clean clean: rm ${OBJECTS} ${EXEC} $ make g++ -std=c++14 -c -o main.o main.cc g++ -std=c++14 -c -o vec.o vec.cc g++ main.o vec.o -o vecs $

the -MMD flag for g++ makes it create .d files which are make dependencies so that we can keep track of what our dependencies are.

$ cat Makefile CXX=g++ CXXFLAGS=-std=c++14 -MMD OBJECTS=main.o vec.o DEPENDS=${OBJECTS:.o=.d} EXEC=vecs ${EXEC}: ${OBJECTS} ${CXX} ${OBJECTS} -o ${EXEC} -include ${DEPENDS} .PHONY: clean clean: rm ${OBJECTS} ${DEPENDS} ${EXEC} $

make is capable of a lot more, but this is sufficient to build most normal C++ projects*

Object Oriented Programming

Introduction

Classes

Coupling and cohesion

There are two important measurements of software design quality, cohesion and coupling

Cohesion measures the amount of "relatedness" that a module or unit of code contains. we want there to be a "high degree" of cohesion.

Coupling measures the amont of dependency between units/modules. We want the amount of coupling between modules to be low, this is because the more dependency each module has the more likely a change in one will cause a change in the other.

Applying these principles

In C we can combine related data together in a structure. In C++ we can also combine functions and data together using the struct keyword. This improves cohesion.

Here is an example using struct:
student.h

#ifndef _STUDENT_H_ #define _STUDENT_H_ struct Student { int assns, mt, final; float grade(); }; #endif
#include "student.h" float Student::grade() { return assns * 0.4 + mt * 0.2 + final * o.4; }
#include "student.h" #include <iostream> int main() { Student s{ 60, 70, 80 }; std::cout<< s.grade() << std::endl; }

All class methods have a hidden first parameter called this which is a pointer of class type and points to the object which the method is being invoked upon.
We can rewrite our previous code as

float Student::grade() { return this->assns * 0.4 + this->mt * 0.2 + this->final * 0.4; }

Warning some people hate the use of this unnecessarily and feel it should only ever be used when needed to disambiguate parameter or method calls since it clutters up the ocode.

Initializing objects

C++ classes have a special type of method called a constructor

Name-of-Class-Type( parameter-list ) { // necessary code }

So using constructors our new implementation file becomes

#include "student.h" int capGrade( int grade ) { if ( grade < 0 ) return 0; if ( grade > 100 ) return 100; return grade; } Student::Student( int assns, int mt, int final ) { this->assns = capGrade( assns ); this->mt = capGrade( mt ); this->final = capGrade( final ); } float Student::grade() { return assns * 0.4 + mt * 0.2 + final * 0.4; }

The preffered syntax in modern C++ is uniform intialization syntax and is of form:

Student s{ 60, 70, 80 }; int x{ 5 }; std::string word{ "hello" }; Node * ptr = new Node{ 10, nullptr };

we can overload our constructors

we can use default parameters on our constructors, these go in the interface and not the implementation file.

Special Class Members

Default constructors

By definition a default constructor is a constructor that has 0 parameters.

If you do not define any constructor to your class the compiler will give you a defualt constructor.

Initializing constants and references

what if we want to intialize constants in an object (for example student id in a student object)

so we use

Member initialization lists (MIL)

after the parenthesis of a constructor we add a : followed by a list of data field names to be initialized

#include "student.h" int capGrade( int grade ) { if ( grade < 0 ) return 0; if ( grade > 100 ) return 100; return grade; } Student::Student( const int id, int assns, int mt, int final ) : id{ id }, assns{ capGrade(assns) }, mt{ capGrade(mt) }, final{ capGrade(final) } {} float Student::grade() { return assns * 0.4 + mt * 0.2 + final * 0.4; }

It is normally considered poor practice to use the body for anything the MIL could have done

Copy constructors

There are other methods the compiler provides if you don't provide your own

  1. default constructor: calls the default constructor on all fields that are objects
  2. copy constructor: copies all fields from the object passed in
  3. copy assignment operator: copies all fields from the object passed in
  4. destructor: does nothing by default
  5. move constructor: takes data from the object passed in
  6. move assignment operator: takes data from the object passed in

a copy constructor has a parameter which is a constant reference to an object of the same type

Student( const Student & other ) : assns{other.assns}, mt{other.mt}, final{other.final} {}

The default copy constructor does not work when we want to copy a dynamically allocated data structure.

Node(const Node &n) { data = n.data; if ( n.next != nullptr ) { next = new Node{ *n.next }; } else { next = nullptr; } }

For now, we are going to say that a copy constructor is called when an object:

  1. is initialized by another object
  2. is passed by value
  3. returned by value

The Peril of single-argument constructors

By definition a single argument constructor implicitly convert an argument of the specified type into an object of the construcor type.

struct Node { ... Node( int data ) : data{data}, next{nullptr} {} }; int f(Node n) {...} Node n1{4}; // single-argument ctor call Node n2 = 4; // implicit conversion from int to Node via single-arg ctor f( 4 ); // 4 implicitly converted to a Node

if we want to disable implict converstion we can lable all single-argument constructors with the explicit keyword

struct Node { int data; Node *next = nullptr; explicit Node(int data) : data{data} {} Node(int data, Node *next): data{data}, next{next} {} Node(const Node &n): data{n.data}, next{n.next ? new Node{*n.next} : nullptr} {} }; Node myNode = 4; // Causes an ERROR

Destructors

The destructor provided by the compiler does nothing but call destructor of data fields which are objects

the steps that occur when a destructor is run are:

  1. run the body of the destructor
  2. invoke destructors for the object's data fields that are themeslves objects. This occurs in reverse declaration order.
  3. Deallocate the space associated with the object

the signature for a class destructor follows the format:

~class-name();

Header file

struct Node { int data; Node *next; Node(int data, Node *next); Node(const Node &n); explicit Node(int n); ~Node(); };

Here is the destructor as it would appear in the implementation file

Node::~Node() { delete next; }

Copy assignment operator

We can copy an object by assigning it to another object. This uses the copy assignment operator which performs a shallow copy of the data fields just like the implicit copy constructor.

the name of the operator is operator= and by definition it takes a constant reference of the class type as its single parameter.

class-type & operator=( const class-type & parameter-name );

Here is an example of a copy assignment operator implementation

Node & operator=( const Node & other) { if ( this == &other ) return *this; data = other.data; Node * tmp = other.next? new Node{ *other.next } : nullptr; delete next; next = tmp; return *this; }

Copy-swap idiom

There is another approach by using the copy-and-swap idiom where we create a local copy which is automatically destroyed. and if it is succesfully created we swap using std::swap

#include <utility> struct Node { ... void swap( Node & other ) { std::swap( data, other.data ); std::swap( next, other.next ); } Node & operator=( const Node & other) { Node tmp{ other }; swap( tmp ); return *this; } ... };

Move semantics

There are situations (such as passing an argument as a parameter) where the compiler will need to create a temporary object and then later copy this object to create the final result.

Move constructor

The introduction of an rvalue reference now lets us declar a constructor which takes in an rvalue reference.

Ad move constructor is designed to steal the information from the rvalue passed into the constructor

class-type( class-type && parameter-name ) {...}

The rvalue passed through is eventually destroyed by the call for its destructor so we have to ensure that we save the information we need.
In the example of the node structure we have:

struct Node { ... Node( Node && other ); ... }; ... Node::Node( Node &&other ) : data{other.data}, next{other.next} { other.next = nullptr; }

Move assignment

Move assignment is similar to copy assignment. We need to make sure we don't leak memory.

struct Node { ... Node & operator=( Node &&other ); void swap( Node &other ); ... }; ... Node & Node::operator=( Node &&other ) { swap(other); return *this; } void Node::swap(Node &other) { std::swap( data, other.data ); std::swap( next, other.next ); }

Rules for replacing default compiler operations

|---|---|--| |Default constructor| if no other constructors| does nothing| |Destructor| if no destructor| does nothing| |Copy constructor| if no move constructor and no move assignment| copies all members| |Copy assignment| if no move constructor and no move assignment| copies all members| |Move constructor| if no destructor, no copy constructor and no copy nor move assignment| moves all members| |Move assignment| if no destructor, no copy constructor and no copy nor move assignment| moves all members|

This leads us to the rule of 5, generally if u define one of the following u will need to define the rest

  1. copy constructor
  2. copy assignment operator
  3. destructor
  4. move constructor
  5. move assignment operator

Member operators

if we are invoking an operation, the object must be on the left hand side

struct Vec { int x, y; Vec operator+( const Vec & other ) { return {x + other.x, y + other.y}; } Vec operator*( const int k ) { return { x * k, y * k }; } };

Must be class members:

Must not be class members

Static Members

If we want to have values which are the same across all objects of a certain type (value belongs to the class rather than the individual objects), for example the number of students, then we need to use a static member.

Static members are associated with the class itself and not any particular instance of the class:

// In student.h struct Student { . . . static int numInstances; Student(int assns, int mt, int final): assns{assns}, mt{mt}, final{final} { ++numInstances; } }; // In student.cc: int Student::numInstances = 0;

Static member functions: don't depend on a specific instance for their computation (they don't have an implicit this parameter).

// In student.h: struct Student { int assns, mt, final; static int numInstances; . . . // The static method howMany() can access the static field numInstances. // However, it cannot access the instance fields assns, mt, final. static void howMany() { cout << numInstances << endl; } }; // In main.cc: Student billy {60, 70, 80}, jane {70, 80, 90}; Student::howMany(); // 2

Advanced object use

Object arrays

To create an array of objects the class must provide a default constructor, otherwise it's a syntax error

This cannot be used in an array:

struct Vec { int x, y; Vec( int x, int y ); };

However this can be used in an array:

struct Vec { int x, y; Vec( int x, int y ); };

If the class we're working cannot/should not introduce a default constructor, then the only alternative is to create an array of pointers to the class type

Constant Objects

Constant object (const object) is an object whos fields cannot be modified.

// const is part of a function's signature, so it must be written in both .h and .cc float Student::grade() const { return assns * 0.4 + mt * 0.2 + final * 0.4; }

Mutable fields

struct Student { . . . mutable int numMethodCalls = 0; float grade() const { // can be const now ++numMethodCalls; // OK now return . . . ; } };

Say we want to track how many times a method is called to track performance. The variables which counts the number of times the method is called only affects the phyiscal constness of the object rather than the logical constness (its value changing does not affect any of the logic an outside user would observe).

We can define mutable fields which means the can be changed even in constant objects

Best practices

Invariants and Encapsulation

Sometimes we need to enforce certain proper use of classes or other things in our code so that errors cannot be introduced. For example:

struct Node { int data; Node *next; Node (int data, Node *next): data{data}, next{next} {} . . . ~Node() { delete next; } }; int main() { Node n1 {1, new Node{2, nullptr}}; Node n2 {3, nullptr}; Node n3 {4, &n2}; }

Encapsulation

We can regain control of our classes through encapsulation, by setting the access modifier or visibility for each one of the members of a class.

For example:

struct Vec { Vec (int x, int y); // By default, members are public private: // What follows is private; cannot be accessed outside struct Vec int x, y; public: // What follows is public; accessible to all Vec operator+(const Vec &other); . . . };

The class Keyword

By default all members of structs are public, but in general we want fields to be private and only methods should be public. So it would be better if the default visibility way private.

We achieve this with the struct keyword

class Vec { int x, y; // These are private. public: Vec (int x, int y); Vec operator+(const Vec &other); . . . };

Accessor and Mutator Methods

Since fields of objects are private, we use acessor and mutator methods to read and change the values.

class Vec { int x, y; public: . . . int getX() const { return x; } // accessor void setX(int z) { x = z; } // mutator int getY() const { return y; } // accessor void setY(int z) { y = z; } // mutator };

Enforcing encapsulation with accessors and mutators

We should only create accessors and mutators when necessary. If certain invariants are needed for mutators they are implemented in the mutator methods (for example grade must be between 0 and 100)

here is a fixed implementation of our linked list class list.h:

class List { struct Node; // Private nested class; only accessible inside List Node *theList = nullptr; // Must be nullptr or pointer to heap-allocated object public: void addToFront(int n); // Adds an element to the front of the list int ith(int i); // Retrieves the element in the ith position of the list ~List(); };

list.cc

struct List::Node { // Nested class int data; Node *next; Node (int data, Node *next): data{data}, next{next} {} ~Node() { delete next; } }; List::~List() { delete theList; } void List::addToFront(int n) { theList = new Node(n, theList); } int List::ith(int i) { Node *cur = theList; for (int j = 0; j < i; ++j, cur = cur->next); return cur->data; }

Friend Classes

In our implementation of node the client cannot access nodes directly and must call ith function many times to find it which costs O(n2n^2) time.
We can fix this by making node a public class but with the construct being private (so the client cannot create a node).

class List { public: class Node { // Public nested class int data; Node *next; Node (int data, Node *next); // Constructor is now private! public: ~Node(); int getData() const; Node *getNext() const; friend class List; // List has access to all members of Node } private: Node *theList = nullptr; // Private internal state public: void addToFront(int n); // Adds an element to the front of the list int ith(int i) const; // Retrieves the element in the ith position of the list Node *getNodeAt(int i) const; // Retrieves the Node in the ith position of the list ~List(); };

You should use friends as little as possible since it weakens encapsulation

Friend Functions

class Vec { int x, y; }
// vec.h class Vec { int x, y; friend std::ostream &operator<<(std::ostream &out, const Vec &v); }; //vec.cc std::ostream &operator<<(std::ostream &out, const Vec &v) { return out << v.x << ' ' << v.y; }

Once again this weakens encapsulation

Unified Modelling Language

The Unified Modelling Language (UML) is a visual modelling language that lets people design and document a software system.

We will be looking onlt at the subset of notation for class models

Class models

Martin Fowler's "UML Distilled: Third Edition" is a very good reference (focus on chapter 3 and 5)

Class model notation

Classes

Class models contain 3 boxes

  1. containes the class name
  2. the second box is optional, and contains atributes
  3. the third box is optional, and contains operations

Comments

A comment can be added to the class diagram by joining a rectangle with a bet uppr right corner ("dog ear") to the item being annoted with a dashed-line.

Attributes

Attributes are left-justified and written in the regular typeface. Describe the information held by an instance of the class and may be replaced by association needs

The general syntax for an attribute is:

≪stereotype≫ visibility / name : type multiplicity initial-value {property}

Operations

operations are left-justified and written in regular type face. They are shown when needed though a full description must be provided at least once.

abstraction operation is italicized.

If the operatio is static the name and type strings are underlined

examples:

- display () : Location + hide () ≪constructor≫ + create () - attachXWindow( xwin : XWindow* ) # Matrix::transform (in distance: Vector, in angle: Real = 0) : Matrix

Class relationships

  1. aggregation
  2. composition
  3. generalization

Association

Tells us very little other than that a relationship exists

Aggregation

Describes a "whole-part" relation where the aggregate (or whole) is made up of the constituent parts if A has a B then typically:

Composition

Composition is a stricter form of aggregation. Once a part is joined to a "whole" it may not be shared with any other object.

The whole is responsible for destroying all of its component parts when it is destroyed

An example of the relation is a Point to a Polygon or a Circle (a point may belong to an object of either type but not part of borth simultaneously).

Generalization/specialization

The generalization (or specialization) association between the parent/super class and the child/sub class is indicated by putting a triangular arrowhead on the association end that joins the parent. By definition, there is no multiplicity or navigation arrow head, though constraints may be added. There may be separate lines from the parent class to each child, or the lines may be drawn as a tree structure.