Permission information: d rwx r-x ---
d if directory, - if filer), write (w), executable (x)Changes group-name associated with a file
Usage: chgrp [-R] group-name file/directory-list
Changes permissions of a file
Usage: chmod [-R] mode-list file/directory-list
mode-list has the form : security-level operator permissionu), group (g), other (o), all (a)+ adds permission, - removes permission, = sets permissionExample: 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
712 -> 111 001 010 -> rwz --x -w-path: is the general name of a file or directory in textual format
Note: directories in linux are just a specialized form of file
/ is the root directory
. is the current directory, .. is the previous directory
cd to change directory
pwd to display path of working 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.
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
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
lsThe command ls -l displays a long form of the list with the following information:
- for a file, d for directorybash can run in an interactive (user provides commands) or non-interactive mode (a script file)
command prompt is what the shell displays in interactive mode when it is waiting for user input
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
catcat simple reads the contents of standard input and writes it back to standard 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
stdin being the keyboard it will be file1.txtyou can also redirect the standard output using >
cat > file2.txt
file2.txtyou 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
log.txtyou can pass arguments to a program or script by writing each argument separated by a space after the command name:
cat -n file1.txt
-n argument makes cat prefix each line with a line numbercat -n < file1.txt essentially dose the same thing as cat -n file1.txt but they are different
stdin so that it's file1.txtthe program echo reads each command-line argument to stdout
$ echo a file1.txt
a file1.txt
$ echo a < file1.txt
a
$
file1.txt is not printed because its not an argument (its an instruction for the shell to redirect stdin)
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 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
head -n gives the first n lines of a filewc -w counts the words in the inputWe can combine these two programs by piping them. A pipe is made using the the character |
head -20 file.txt | wc - w
file.txtcat file.txt | head -20 | wc -w > words.txt
file.txt to headhead which is passed to wc and finally the number of words is redirected to words.txtNote: echo changes whitespace of a file, do not combine echo with cat if u need to preserve the original file format
The shell can automaticall expand a few wildcard patterns to match all the files that satisfy the pattern.
cat *.txt
*.txt is known as a globbing pattern, the wildcard * means "match any sequence of characters>"The following operators can be used in globbing patterns
* : matches zero or more characters? : matches zero or one character+ : matches at least one character[abc] : matches exactly one of the characters in the brackets[!abc] : matches any character except the ones in the brackets[a-z] : matches any character in the given range{pat1, pat2} matches either pat1 or pat2 (note no spaces)We will use the tool egrep which looks for lines that match a pattern.
grep is the less powerful predecessor of egrep$ 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
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
* repeatable, it will match to either 0 or any number of repetitions of the space* to + which means at least one of the repetition must exist$ egrep "^(CS|cs)246 +:" < tasks.txt
cs246 : Exam 1
e matches to "e"(XYZ) groups patterns, usually in order to use |,*,or + on a whole group
(CS246)* matches to "" or "CS246" or "CS246CS246"(X|Y) matches either X or Y[...] matches any of the characters between the square brackets
[cC][sS] is equivalent to (c|C)(s|S)[...] can also match ranges of characters, specified with a-z.
[a-z0-9] matches all lower case letters and numbers[a-df-z] matches all lower case letters except for "e"[^...] is an inversion of [...] (matches anything except what's specified)
[^a-z] matches anything other than a lower-case characterCS[^3]46 will not match to "CS46" but will match "CS246"* matches repetition of a pattern 0 or more times
(c|C)* matches "cCCCcccCCcCCC"+ matches repetition of pattern 1 or more times? matches repetition of a pattern 0 or 1 time.
a? matches either "" or "a". matches any single character. Often used to combined patterns that are separated by random tings
(CS246.*ANTH221|ANTH221.*CS246) matches to ant and cs with anything between^ matches beginning of line
^CS246 matches to the line that starts with "CS246"$ matches end of line
CS246$ matches to the line that ends with "CS246"^CS246$ matches to the line that is exactly "CS246"\ escapes special characters
\ on its own so you should use it in single quotes (which will not interploate)Here's an example
$ egrep "^(CS|cs)2[0-9][0-9] *:.*[Aa]ssignment" < tasks.txt
CS241: Finish assignment 1
CS246: Assignment 2
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
It is convention, but not necessary, to use .sh for bash script files
#!/bin/bash
date
whoami
pwd
-x can be added to show verbose output
we can run the program by telling bash to execute it basic basic.sh
The general rules for setting up a script file are:
adding -x will make the script show every command and its arguments as it executes
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
= operator, otherwise its an errorit 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
$0 the first parameter of the command-line and its arguments; the shell-script name$1, $2, etc each command-line argument, based upon its position$# the total number of command-line arguments$? the exit/return value of the most recently executed command; used to tell us whether it succeeded or failed
#!/bin/bash
egrep "^$1$" /usr/share/dict/words
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
if/elif you must separate it with a semicolon from the conditiona 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 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 ${?}' ${?}
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
$(( ... )) is used to tell the shell that the information within the doubled parentheses are to be treated as integers.here is a list iteration loop:
for variable in list; do
command1
command2
...
done
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.
Unit tests
Integration tests
Functional tests (system tests)
Acceptance tests
Regressions tests
Performance tests
White box tests:
Black-box tests:
Grey-box tests:
Creating black-box test:
creating white-box tests
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.
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
.h, because .h represents that it's a C library and this is a C++ librarystd:: specifies that something is defined in the standard (std) namespace
std::cout is the name for the standard output streammain 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
.cc in this courseYou 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
-g roduce debugging information in the operating system's native format. The GNU debugger, gdb, can work with this debugging information. Makes your code larger, but useful while trying to get everything working.-c Produce an object file (ends in .o) that consists of assembler output. Will be useful once we discuss separate compilation.-Wall This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning). Not necessary, but a good idea.Wextra This enables some extra warnings that aren't enabled by -Wall. Not necessary, but a good idea.Wpedantic This ensures that your code follows the strict ISO C++ standard, with no forbidden extensions. Not necessary, but a good idea.-D Lets us define a macro name as a command-line argument to the compiler. Useful for selectively adding/removing code during the compilation process.It is strongly recommended to learn a tool such as gdb for debugging
There are three golbal variables in the standard (std) namespace whcih define stream objects used for basic input and output
cin = stdin (in C) : reads from standard inputcout = stdout (in C) : writes to standard outputcerr = stderr (in C) : writes to standard error
>> is the operator to read input from the stream<< is the operator to write to the output streamiostream libraryThe 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()) { ... }
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;
}
}
(!cin) is equivalent to cin.operator!() where cin's operator ! has been defined to return the contents of the fail bit by calling fail()
Version 3:
cin >> i is equivalent to operator>>(cin, i)
operator>> has return type cin since it must be able to read from input multiple timescin >> x >> y >> z is equivalent to `operator>>( operator>>( operator>>( cin, x), y), z);operator>> is a refnerence variable since cin needs to be able to modify itthe 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
cin keeps reading till a non-integer then sets the fail bit we need tocin.clear()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;
}
}
}
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;
}
}
(const char *) or the type (const string &).*if input file cannot be opened for input
fail bti is set and u can chek it with fail()if output file doesn't exist
if output file doesn't have write permissions
fail bit is setThe files will automatically close for us when the objects go "out of scope" and are destroyed on the final closing brace } of the program.
open() to open the file you must remember to close() it when you are doneWe 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;
}
}
setw is to set width of the information to 3 characters, the fill-character is used to fill out information to meet widthdec, oct, hex are used to print different "base" systems#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
dec/oct/hex feature is "sticky" as in once it's set it continues to print in that base until we change it againshowpoint is used to force printing of decimal point in our floating point numbersetprecisions specifies number of digits after the decimal point to print, uses 0 as the fill character| 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" }; |
sthese are a few of the common string oeprations/operators
s1 == s2s1 != s2s1 <= s2, s < s2, s1 >= s2, s1 > s2
s1.size() or s1.length()s1[0], s1[1], ...
0 and goes to s1.size() - 1s1 = s2 + s3; s3 += s4;>> skips initial whitespace when reading std::stringgetline takes an input stream as a parametergetline does not skip initial white spacegetline can be coerced to return a boolean valueThere 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.
stringstream for input or output its recommended to use istringsream or ostringstream as appropriate.The primary purpose of an input string stream is to take an existing string and split it into separate words.
isstringstream separates the words by whitespace#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;
}
}
getline to specify a delimiter to separate our string based on commas for s2There 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 in C++ are the same as in C: The main function may take two arguments, argc and argv
argc is the number of of arguments the program receivedargv is the array of argumentschar ** not an array of strings#include <iostream>
int main(int argc, char **argv) {
for (int argi = 0; argi < argc; argi++) {
std::cout << argv[argi] << std::endl;
}
}
argv[0] is the name of the program itselffunctions in C++ are very similar to C. Basic format:
return-type function-name( type1 arg1, type2 arg2, ... ) {
...
return value of appropriate type;
}
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.
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
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.
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 };
typedefstruct doesn't need to repeated in all variable declarations. Just needs to be done once in the initial type definitionNULL instead you should use nullptr}Here is an incorrect example:
struct Node {
int value;
Node next;
};
Node is not defined until the end of the closing bracket. You can use a pointer since they all have the same sizeWe 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
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 );
inc(x) to workReferences 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;
*ptr contains the address of xThere are a number of things that cannot be done with an lvalue reference
int &x; is illegal, must be initialized with an lvalueint &*x; is illegal
int &&x; does not mean "reference to reference" we will see what it actually means laterint $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 ) { ... }
| 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.
Node * nodeArray = new Node[10];
...
nodeArray[0].data = 5;
nodeArray[0].next = nullptr;
...
delete [] nodeArray;
[] after delete otherwise it will only delete the first element and cause a memory leak
new and delete statements, if one used [] the other should too./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
There are three ways a function can return values;
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;
}
delete what's allocatedNode & newNode = getMeANode( 5 );
...
// do something with newNode
...
delete &newNode;
delete only works on pointersWhich technique should we use
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;
}
(v * k) so we have to define it both waysstruct 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:
std::osteram &operator<<std::ostream &return statement to return whatever the name of the output stream isstd::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:
std::istream &operator>>std::istream &return statement to return whatever the name of the input streamtemplates:
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;
}
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
We split our code into two components:
.h (for "header").cc. C files are always named .cThe 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
$
-c compiles to an object file which is compiled code but not enough for a full program..o files is called linkingif 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.
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
$
make automatically only rebuilds what is needed based on what we changedwe 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*
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.
stdio library contains input and output functions so it's highly cohesiveCoupling 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.
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.
structHere is an example using struct:
student.h
#ifndef _STUDENT_H_
#define _STUDENT_H_
struct Student {
int assns, mt, final;
float grade();
};
#endif
grade which takes no parameters and returns the final grade
studnet.cc#include "student.h"
float Student::grade() {
return assns * 0.4 + mt * 0.2 + final * o.4;
}
:: prefixed by the class name to specify that the grade function is a method of the student classC::f
C, f is in the context of C
main.cc the client code#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.
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;
}
this to differentiate between the parameters and the actual data field namesThe 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.
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.
what if we want to intialize constants in an object (for example student id in a student object)
so we use
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;
}
{} in the MIL is the data field, the name inside is the parameter nameIt is normally considered poor practice to use the body for anything the MIL could have done
There are other methods the compiler provides if you don't provide your own
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:
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
Node myNode = Node{4};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:
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;
}
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;
}
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;
}
...
};
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.
type&&) which tells the compiler to not perform the whole move/copyThe 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 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 );
}
|---|---|--| |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
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
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
Student class, and not on any objectTo 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 object (const object) is an object whos fields cannot be modified.
const className obj or pass the object as a constant f(const className &obj)const; added to their signature on constant objects because that promises that the fields won't be modified
for example:// 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;
}
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
constconst so that constant objects can be passed to itSometimes 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};
}
n3 is called it can cause the program to crash since it is trying to delete an object in the stack not the heap.nullptrWe can regain control of our classes through encapsulation, by setting the access modifier or visibility for each one of the members of a class.
this pointer of the object's methods)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);
. . .
};
class KeywordBy 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
struct and class is the defualt visibilityclass Vec {
int x, y; // These are private.
public:
Vec (int x, int y);
Vec operator+(const Vec &other);
. . .
};
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
};
getField and setField
constWe 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();
};
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;
}
In our implementation of node the client cannot access nodes directly and must call ith function many times to find it which costs O() 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
class Vec {
int x, y;
}
operator<< needs to see them so it must be a friend function
We implement it as// 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
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
Martin Fowler's "UML Distilled: Third Edition" is a very good reference (focus on chapter 3 and 5)
Class models contain 3 boxes
Banking::CheckingAccount)≪controller≫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 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 are left-justified and written in regular type face. They are shown when needed though a full description must be provided at least once.
voidabstraction 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
Tells us very little other than that a relationship exists
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 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).
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.