of 47
8/6/2019 MyCSC2402Notes
1/47
y Memory
Memory stores data and programs. There are two kinds of memory - primary storage
(including RAM and ROM) and secondary storage (usually a hard disk).
Note: ROM is read-only memory that contains code needed to start the computer.
y Bus
The CPU, RAM memory, and the electronics controlling the hard disk and other
devices are interconnected through a set of electrical lines called a bus.
y Program instructions and data are stored on the hard disk, on a CD -ROM, or
elsewhere on the network. When a program is started, it is brought into RAM
memory, from where the CPU can read it. The CPU reads the program one
instruction at a time. As directed by these instru ctions, the CPU reads data, modifies,
it and writes it back to RAM memory or the hard disk.
y Register
A register is the storage location in the CPU.
y Machine instructions (Machine codes)
Machine instructions are encoded as numbers. On a processor from a different
manufacturer, the encoding would be quite different.
8/6/2019 MyCSC2402Notes
2/47
y Assembly
Easier to read (by assigning short names to commands). Another computer program
called assemblertranslates it into machine codes.
The assembly instructions still differs from one processor to another.
y higher-level programming language
Translated by a special computer program called compilerinto machine codes.
Higher-level languages are independent of the underlying hard-ware. They are
compiled to different code on different processors.
y #include
A C++ standard library header file containing function prototypes for the C++
standard input and standard output functions.
Allows program to output data to the screen or input data from the keyboard.
eg.fix
y #include
A C++ standard library header file containing function prototypes for stream
manipulators that format streams of data.
eg. setprecision(), setw()
y #include
A C++ standard library header file containing definition of class string.
Also enable the use of the function getline.
y #include
A C++ standard library header file containing function prototypes for math library
functions.
eg. pow(x, y); sqrt(x); log(x); log10(x); ceil(x); floor(x); fabs(x);
y #include
A C++ standard library header file containing function prototypes.
eg. rand(), srand(seed), abs(x);
8/6/2019 MyCSC2402Notes
3/47
[Note: rand() yields a random integer between 0 and RAND_MAX. ]
To yield a random number between a and b:
int r = a + rand() % (b - a + 1);
y using namespace std
allow us to use cout, cin, endl directly instead of writing stdcout, stdcin,
stdendl.
y Compile-time error (syntax error)
Something is wrong according to the language rules. Source code will not compile.
y Run-time error (logic error)
The program is syntactically correct but doesnt do what it is supposed to do. The
compiler cannot find the error.
y Overflow error
Computers can make overflow errors when you ask them to perform computations
whose results falls outside their numeric range.
y Library
Library is a collection of code that has been programmed and translated by someone
else, ready for you to use in your program.
y The compilation process
8/6/2019 MyCSC2402Notes
4/47
Program statements are entered into a text editor. The compiler translates the C++
source code (that is, the statements that you wrote) into machine code.
Note that the machine code contains only the translation of the code that you wrote.
That is not enough to actually run the program. A special program called linkertakes
your machine code file and the necessary parts from the library (eg. iostream library)
and builds an executable file. The executable file is usually ended with .exe
Note: a library is a collection of code that has been programmed and translated by
someone else, ready for you to use in your program.
Also the machine code has an extension of .obj or .o.
y Constants
Constants must be initialized when declared.
const type_name variable_name = initial_value;
y Variable Defn
variables names must start with a letter or underscore,, and the remaining
characters must be letters, numbers, or underscores. p.35 Big C++
y Number types
The name for the floating-point number used is double.
To write numbers in exponential notation in C++, use an En instead x10n. For
example, 5.0 x 10-3
becomes 5.0E-3.
Putting a floating-point value into a intvariable, the fractional part will be lost. (This
is not necessarily the closest integer)
Note that when dividing two integers, the result is always an integer, with the
remainder discarded. eg. 7/4 = 1
Division works as expected, as long as at least one of the numbers involved is a
floating-point number.
Note that short (16 bit) and long (64 bits) are integer types.
y Rounding to the closest integer
8/6/2019 MyCSC2402Notes
5/47
static_cast(x + 0.5)
[Note: here x is a floating number]
y \n
Note that this is a special character.
eg. stdcout Welcome to C++\n;
Position the screen cursor to the beginning of the nex t line.
y static_cast(2.6);
change it to an integer by truncating (or similarly round down).
y String are enclosed in double-quotes.
String is a sequence of characters. Strings are enclosed in quotation marks.
This enables the compiler to consider them as plain text and not program
instructions.
eg. Hello
Note: to include double quote in a string, use escape sequence.
eg. \Hello \
Unlike number variables, string variables are guaranteed to be initialized. They are
initialised with the empty string.
[Note: There is another data type char, used to denote individual characters.
individual characters are enclosed in single quotes.]
Name Purpose
s.length() the length of s
s.substr(i) The substring of s from index i to the end of
the strings.substr(i, n) The substring of s of length n starting at
index i
getline(f, s) Read string s from the input stream f
8/6/2019 MyCSC2402Notes
6/47
y Lengths ofstrings
The number of characters in a string is called the length of the string. blank space
and newline character are count as one character only.
eg. str.length()
y Concatenation
The + operator concatenates two strings. However, one or both of the strings
surrounding the + must be a string object.
y Output formatting
To format output, include the line:
#include
Output can be formatted with functions from the iomanip library such as:
setw(): Sets the field width of the next item only.
left: Selects left alignment.
right: Selects right alignment (default).
fixed: Selects fixed format (6 digits after the decimal point)
for floating point numbers.
setprecison(): Sets the number of significant digits for general format;
Sets the number of digits after the decimal point for
fixed format.
eg. coutfixed setprecision(2)
[Note: setprecision andfixedmanipulators need only to be used once. However,
setwmust be specified anew for every item.]
Also see p.97 C++ How to program
8/6/2019 MyCSC2402Notes
7/47
y ABOUTCIN
By default, leading whitespace (carriage returns, tabs, spaces) is ignored (while
consumed from the buffer) by cin.
Keyboard input is buffered. When the user hits the En ter key, all input is placed into
a buffer.
eg. Suppose you enter
8 0 4 3 then Enter
Buffer = 8 0 4 3 \n
When entering multiple values in a line, all that matters is that the values are
separated by white space: that is, blank spaces, tabs, or newlines.
That is, the values in the buffer are read one by one separated by a blank space, tab,
newline or something unexpected. Note that cin does not consume the following
white space, typically a newline \n. That is, the white space following the value read
into cin is still in the buffer. But note that leading white spaces are ignored as said
above.
When cin encounters something unexpected, it will also set itself to a failed state,
and all subsequent input statements will be ignored. The something unexpected
will still be in the buffer. We can test the state ofcin by the cin.fail()
Note: whatever is remained in the buffer stays until being cleared
Ifcin is in a fail state, then cin.fail() is true.
how to use cin.clear()
#include
using namespace std;
int main(){
int x = 0;
int y = 0;
cin >> x;
cin.clear();
string z;
cin >> z;
8/6/2019 MyCSC2402Notes
8/47
cin >> y;
cout str;
cout
8/6/2019 MyCSC2402Notes
9/47
8/6/2019 MyCSC2402Notes
10/47
y getline
The getline command reads all keystrokes until the Enter key.
eg. getline(cin, name)
Reads all keystrokes until the Enter key and places it into the name variable.
The getline function reads an entire line of input, consuming also the newline
character at the end of the line. But only places characters before the newli ne
character into the variable. It DOES NOT place the newline character into the
variable. Note that since the newline character is consumed, it is no longer in the
buffer.
(Note: the newline character counts as one character only. See p.63 Big C++)
In other words, the getline function reads characters until the newline character is
encountered, places the characters in a stringvariable and discardsnewline
character.
y Enumerated Types
eg. enum Weekday{MONDAY, TUESDAY, WEDNESDAY};
homework_due_date = WEDNESDAY;
Note that: couthomework_due_date gives 2.
Note: homework_due_dat = 1; is a compile time error.
y Time Objects
Time x = Time();
Time x = Time(23, 59, 59);
Time x; //This invokes the defaultconstructorofthe class See p.70 Big C++
Time x(19, 0, 0);
Time x() WRONG
Name Purpose
Time() Constructs the current time
Time(h, m , s) Constructs the time with hours h, mintues
m, and seconds s.
t.get_seconds() Returns the seconds value oft
t.get_minutes() Returns the minutes value oft
t.get_hours() Returns the hours value oft
t.add_seconds(n) Changes tto move by n seconds
t.seconds_from(t2) Computes the number of seconds between t
8/6/2019 MyCSC2402Notes
11/47
and t2.
To use time class, include the header file that contains its declarations:
#include ccc_time.h
[Note: we use instead of < > because the file is not part of the standard C++ headers .
Also, ccc_time.h should be in the same directory as the application file.]
To compile the program, in MinGW, use
g++ -o myapp time.cpp ccc_time.cpp
Here, myapp is the name of the final executable file, time.app is the file that contains the
main() and ccc_time.cpp is the file that contains the definition of Time class.
y About vector
C++ provides a standard template container called vector.
To use vectors, include the line:
#include
Vector allows us to store a collection of data items of the same type. For example:
vector my_int; // my_int is a vector of integers
vector my_string; // my_string is a vector of strings
To store data to a vector, use the member function push_back():
int iNum =123;
my_int.push_back(iNum); // my_int holds 123 at index 0
my_int.push_back(456); // my_int holds 456 at index 1
string str= Hello!;
my_string.push_back(str); // my_string holds str at index 0;
y Relational operators
Relational operators (< >= !=) can be used to compare strings. They are
compared in dictionary order. But note that C++ is case sensitive and sorts
characters by listing numbers first, then uppercase characters then lowercase
characters. When comparing strings, corresponding characters are compared until
8/6/2019 MyCSC2402Notes
12/47
one of the strings ends or the first difference is encountered. If one of the string
ends, the longer string is considered the later one. p.106 Big C++
Note: relational operators cannot be used to compare objects of arbitrary classes.
For example, ifs and tare two objects of the Time class, then the comparison s==t is
an error. Also, you can only compare numbers with numbers and strings with strings.
y If-else statements
If(condition){
statement1;
statement2;
}
else if(condition){
statement3;
.
}
else {
statemetn4;
}
An else always belongs to the closest if(when it is not clear which ifit belongs to).
For if-else statement with multiple alternatives, as soon as one of the tests succeeds,no further tests will be attempted.
Note the expression inside if() need not be a logical condition. Any numerica val ue
can be used inside a condition, with the convention that 0 denotes false and any
non-0 value denotes true. p.107 Big C++
Moreover, C++ assignments are also expressions and have values. For example, the
value of the expression a = 5 is 5.
y The Switch Statement
The switch statement consists of a series ofcase labels and an optional default case.
The test cases must be constants, and they must be integers.
The switch statement compares the value of the controlling expression with each
case label. Without break statements, once a match occurs in the switch, the
statements for that case and subsequent cases execute until a break statement or
8/6/2019 MyCSC2402Notes
13/47
the end of the switch is encountered. This is referred to as falling through to the
statements in subsequent cases.
switch(controlling expression)
{
case const1: statement1; break;
case const2; statement2; break;
default: statement; break;
}
y The Selection Operator
test ? value1 : value2
The value of the expression is either value1 if the test passes or value2 if it fails. For
example, we can compute the absolute value as
y = x >= 0 ? x : -x;
which is a shorthand for
if(x >= 0) y = x;
else y = -x;
y Bool
To store a condition that can be true or false, you use a variable of a special data
type bool. That type has exactly two values, denotedfalse and true.
The && and || operators are computed using lazy evaluation. As soon as the truth
value is determined, no further conditions are evaluated. Note that && and ||
returns a true orfalse value. But true andfalse are automatically converted into 1
and 0 respectively in some situations:
ie. cout true; //this gives 1
ie. if(-0.5
8/6/2019 MyCSC2402Notes
14/47
Zero is converted to false and any nonzero value is converted to true. See p.118 Big
C++
y While statements
while (condition){
statement;
}
y For Loop
for (i = start; i
8/6/2019 MyCSC2402Notes
15/47
y rand()
C++ has a random number generator, which produces numbers that appear to be
completely random. Calling rand() yields a random integer between 0 and
RAND_MAX (typically 32767 or 2147483647). Note rand() includes the bounds 0 and
RAND_MAX.
To use randfunction, we must include the cstdlib header.
rand() only produces pseudorandom numbers, to overcome the problem we can
write:
Time now;
int seed = now.seconds_from(Time(0, 0, 0));
srand(seed);
Simply place these instructions at the beginning of your program, before generating
any random numbers. Then the random numbers will be different in every program
run.
To generate a random number between a and b (including the bounds themselves):
int r = a + rand() % (b - a + 1);
y Function Definitionreturn_typefunction_name(type parameter1, type parameter2, , type parametern)
{
statements;
return expression;
}
Note that the first line in the function definition is called the function header.
Starting from { and ending at }, we have the function body. A function definition
must contain a function header and the body of the function.
Note that when the return statement is processed, the function exi ts immediately.
The return statement need not be placed at the end. Also, there can be more than
one return statement in the function.
A function that returns a truth value is called a predicate function.
8/6/2019 MyCSC2402Notes
16/47
The variables in the function header are called parameters (or parameter variables,
formal parameters).
A function call supplies values or expressions for the function parameters. These
values or expressions are called arguments (or parameter value, actual parameter).
That is, when you call a function, its parameter variables are initialized with the
corresponding expressions or values in the function call.
For example:
/**
Computes the maximum of two integers.
@paramx an integer
@param yanother integer
@return the larger of the two inputs
*/
int max(int x, int y){
if(x > y) {
return x;
}
else {
return y;
}
}
Note: A function should not have side effects, for example, disp laying characters on
the screen, updating variables outside the function, terminating the program, etc.
y Type Mismatch
The compiler takes the function parameter and return types very seriously. It is an
error to call a function with a value of an incompatible type. The compiler ONLY
converts between integers and floating-point numbers, but it does not convert
between numbers and strings or objects. For example, you cannot give a string to a
numerical function, even if the string contains only digits.
eg. string num = 1024;
double x = sqrt(num); // Error
Also, you cannot store a numerical return value in a string variable:
string root = sqrt(2); //Error
8/6/2019 MyCSC2402Notes
17/47
y Function Declaration (or Prototype)
A declaration (also called prototype) of a function lists the type of data returned by
the function, the name of the function, the types of its parameters , but it contains
no body.
The parameter names are optional in function prototypes and each function
prototype must end with a semicolon.
[Note: The header of the function definition is similar in structure to a function
prototype, except it must provide the parameters and not jus t their data types.]
return_typefunction_name(type , type, );
Eg.
double abs(double x);
Note that function definition is different from function declaration. Declarations end
in a semicolon, whereas definitions are followed by { } block.
The purpose of function declaration is so that it can be called before it is defined.
y Function Signatures The portion of a function prototype that includes the name of the function and the
parameters is called the function signature or simply the signature. The function
signature does not specify the functions return type. Function in the same scope
must have unique signatures. The scope of a function is a region of a program in
which the function is known and accessible.
y Procedures
A procedure is a function that does not return a value.
y Reference Parameter
type_name& parameter_name
Eg.
int& result
8/6/2019 MyCSC2402Notes
18/47
When we make e into a reference parameter, then e is not a new variable but a
reference to an existing variable, and any change in e is actually a change in the
variable to which e refers in that particular call.
A reference parameter must be bound to a variable in the call, whereas a value
parameter can be bound to any expression. Seep.179 Big C++
y ConstantReference Parameter
const type_name& parameter_name
Changing a constant reference parameter is an error. See p.181 Big C++
y Variable Scope
In a program, the part within which a variable is visible is known as the scope of the
variable.
The scope of a variable that is defined in a function extends from its definition to the
end of the block in which it was defined.
Variables that are defined inside functions are sometimes called local variables.
In other words, variables declared inside functions are known as local variables and
can be used only from the line of their declaration in the function to the immediately
following closing right brace } of the function definition. A local variable must be
declared before it can be used in a function. A local variable cannot be access ed
outside the function in which it is declared. When a function terminates, the valuesof its local variables are lost. (One exception is the static local variable).
Variables that are defined outside functions are called global variables. A global
variable is visible to all functions that are defined after it.
y Precedence
See p.135 of Small C++ How to program
y Commenting Out a Section ofCode
Not all compilers allow nested comments.
ie. /*
/*
*/
*/
8/6/2019 MyCSC2402Notes
19/47
The first */ encountered matches up with the first /*. The */ at the end will cause an
error message.
There is another way of masking out a block of code: by using so -called pre-
processor derectives.
ie. #if 0
..
#endif
Note: if you want to include the block temporarily, change #if 0 to #if 1.
y assert()
What should a function do when it is called with inappropriate inputs?
A good practice is for the function to complain loudly during testing, by printing an
error message that clearly indicates the problem with the parameter value.
The assert macro was designed for this purpose. If the condition inside the assert
macro is false, then the program aborts with an error message that shows the line
number and file name. If the condition inside the macro is true when the macro is
encountered, then nothing happens.
When write a function we should:
(i) Establish clear preconditions for all inputs. Write in the @param comment
what values you are not willing to handle for each parameter. [Note:
preconditions are documented restrictions on the function parameters.]
(ii)Write assertstatements that enforce the preconditions.
(iii)Be sure to supply correct results for all inputs that fulfil the precondition.
Syntax:
assert(expression);
eg. assert(x >= 0);
If the expression is true, do nothing. If it is false, terminate the program, displaying an error
message with the file name, line number, and expression.
8/6/2019 MyCSC2402Notes
20/47
To use assertwe must write:
#include
y Class Defintion
Syntax:
class ClassName
{
public:
constructor declarations
memberfunction declarations(prototypes)
private:
}; //Must have semicolon after the closing brace }
Function prototypes (can be without data name, just the type will suffice) are
declared within the class definition. Functions can be declared and defined within
the class definition. However, most func tions can have very large definitions and
make the class very unreadable. Therefore it is possible to define the function
outside of the class definition using the scope resolution operator " ::". This scope
resolution operator allows a programmer to define the functions somewhere else.
This can allow the programmer to provide a header file .h defining the class and a
.objfile built from the compiled .cpp file which contains the function definitions.
Note that a header file may contain class definitions and function prototypes.
Programs use #include pre-processor directives to include header files.
Note: when not specified, all members of a class (including member functions, data
fields) are private. See Quiz 4 Q10
y Constructor
Constructor is used to initialize an object of the class when the object is created. A
constructor is a special member function that must be defined with the same nameas the class, so that the compiler can distinguish it from the classs other member
functions. An important difference between constructors and other functions is that
constructors cannot return values, so they cannot speci fy a return type (not even
void). Normally, constructors are declaredpublic.
8/6/2019 MyCSC2402Notes
21/47
C++ requires a constructor call for each object that is created, which helps ensure
that the object is initialized properly before it is used in a program - the constructor
call occurs implicitly when the object is created. In any class that does not explicitly
include a constructor, the compiler provides a default constructor - that is, a
constructor with no parameters. If any constructor is provided, the compiler will NOT
provide the default constructor. By the way, a default constructor is a constructor
with no parameters. p.241 Big C++
[Note: For data members that are objects of other classes, the default constructor
implicitly calls each data members default constructor to ensure that the data
member is initialized properly. In fact, this is why a string data member will be
initialized to the empty string - the default constructor for class string sets the string
value to the empty string.]
In the code for the default constructor, you need to worry about initializing only
numerical data fields. The data field for a string is automatically set to the empty
string by the default constructor of the string class. In general, all data fields of class
type are automatically constructed when an object is created, but the numeric fields
must be set in the class constructors.
It is common for a class to have multiple constructors. This allows you to define
object in different ways.
When two function share the same name but are distinguished by their parameter
types, the function name is overloaded. When you construct an object, the compile rchooses the constructor that matches the parameter values that you supply.
Note that the functions which are overloaded do not share the same function
signature.
y Mutator member function
A mutator member function of a class changes the state of the object on which is
operates.
For example, if the class has a single mutator: read. After you call
p.read();
the contents ofp have changed.
y Accessor member function
An accessor member function does not modify the object. It q ueries the object for
some information without changing it.
8/6/2019 MyCSC2402Notes
22/47
Accessor function should be tagged with const. The position of the const keyword
occurs after the closing parenthesis of the parameter list, but before the semicolon
that terminates the function declaration.
ie. double get_x() const; See p.234 Big C++
Note: constshould be attached to both function declaration (prototype) in class
definition and the corresponding function definition.
y The definitions of member functions in a class can come in any order.
See p.253 Big C++
y Implicit and Explicit parameter
The object on which a member function is applied is the implicit parameter. Every
member function of a class has an implicit parameter.
Explicit parameters of a member function are listed in the function definition.
See p.238 Big C++
Whenever you refer to a data field inside a member function, it denotes that data
field of the object for which the member function was called.
See p.238 Big C++
One member function can invo ke another member function on its implicit
parameter. See p.251 Big C++
If you see a function call without the dot notation inside a member function, you first
need to check whether that function is actually another member function of the
same class. If so, it means call this member function with the same implicit
parameter.. See p.252 Big C++
y State of an Object
Each object of a class stores certain values that are set in the constructor and that
may change through the application of mutator functions. These values are
collectively called the state of the object.
y Accessing Data Fields
Only member functions of a class are allowed to access the private data fields of
objects of that class. All other functions - that is, member functions of other classes
8/6/2019 MyCSC2402Notes
23/47
and functions that are not member functions of any class - must go through the
public interface of the class.
Suppose x is an object of the class SampleClass, privateData belongs to the private
data fields of SampleClass and publicData belogs to the public data fields of
SampleClass.
We may use:
x.publicData
But cannot use:
x.privateData
The private data fields are only accessible to member functions of the class.
y Member function definition
return_type ClassNamefunction_name(parameter1, parameter2, , parametern)
[const]opt
{
statements
}
y Constructor definition
ClassNameClassName(parameter1, parameter2, , parametern)
{
statements
}
y Calling Constructors from Constructors
Suppose we have a non -default constructor of a class which contains objects in the
data field.
Before the non-default constructor start initializing those objects, the default
constructors of the class in which those object belongs are automatically invoked. In
fact, the objects will be initialized and then those values are overwritten.
It would be more efficient if we use the following code:
8/6/2019 MyCSC2402Notes
24/47
ClassNameClassName(parameters):field1(expression), ,fieldn(expression)
{
statements
}
ie.
PointPoint(double xval, double yval):x(xval), y(yval)
{
}
This syntax is also necessary to construct objects of classes that dont have a default
constructor.
See p.247 - 248 Big C++
y Operator Overloading
ie.
bool Productoperator>(Product b) const
{
}
p.249 Big C++
y Comparing member functions and Non-member functions
Inside main or another non-member function, it is easy to differentiate between
member function calls and other function call. Member functions are invoked using
the dot notation; non-member functions dont have an object preceding them.
Inside member functions, however, it isnt as simple. One member function can
invoke another member function, and here the dot notation is not obvious, as the
object is an implicit parameter.
y Separate Compilation (Header File +Source Code File - common)
The header file contains:
(a)Definition of classes
(b)Declaration of constants
(c) Declarations of non-member functions (global functions)
(d)Declarations of global variables
8/6/2019 MyCSC2402Notes
25/47
The source files (common) contains:
(a)Definitions of member functions & constructors
(b)Definitions of non -member functions
(c) Definitions of global variables
The main function is not contained in the source file (common) as there are many
potential programs that might make use of the class.
Suppose we have a class MyClass which is contained in the header file myclass .h
Programs that need to use MyClass must include the directive:
#include myclass.h
The following directives are used (in the header file) to guard against the multiple
inclusion of the header file myclass.h:
#ifndefMYCLASS_H
#define MYCLASS_H
#endif
These directives are needed because compiler sees the class definition twice, and it
complains about two classes with the same name. (Sadly, it doesnt check whether
the definition are identical.)
y How to produce an .exe
g++ -c sourceFile.cpp Compiles a single source file into an object file
g++ -o Program.exe source1.o source2.osource3.o
Links a series of objectfiles into a single executable.
-o means "output" and is followed by
a filename
y Vectors
A vector is a collection (sequence) of data items of the same type. Every element of
the collection (sequence) can be accessed separately.
8/6/2019 MyCSC2402Notes
26/47
Syntax:
vector variable_name;
vector variable_name(initial_size);
eg.
vector scores;
vector salaries(10);
Note: The first slot of a vector has an index of 0.
Trying to access a slot that does not exist in the vector is a serious error. This i s
known as bounds error. The compiler does not catch this type of error and the
running program generates no error message. Instead, the program will quietly
corrupt some memory.
Syntax (for accessing an element in a vector)
vector_expression[integer_expression];
When a vector is defined without a size parameter, it is empty and can hold NO
elements. For example, the following codes with cause an error.
vector salaries; //No size given
salaries[0] = 35000;
In the size of a vector is not given, we have to use the function push_back. This
function allows you to start out with an empty vector and grow the vector.
eg. vector salaries;
salaries.push_back(value or expression);
Thepush_backcommand resizes the vector by adding one element to its end.
Another member function of the class vector is pop_back. It removes the last
element of a vector, shrinking its size by one.
eg. vector salaries(10);
8/6/2019 MyCSC2402Notes
27/47
salaries.pop_back(); //Now salaries has size 9
Note that thepop_backfunction does not return the element that is being removed.
If you want to know what that element is, you need to capture it first.
To visit all the elements in a vector, we can use:
for(i = 0; i < v.size(); i++){
do something with v[i];
}
Finally, note that vectors are passed by values by default. We can use & if we would
like to pass by reference. See p.276 Big C++
Note: An uninitialized integer vector has values zero stored.
ie. vector num(3); //the 3 elements of the vector is zero.
y Vector as parameters
Pass by value
return_typefunction_name(vector variable_name, );
Pass by reference
return_typefunction_name(vector& variable_name, .);
Pass by constant reference
return_typefunction_name(const vector variable_name, );
y What are Strings?
The term, string, is used in C to describe a contiguous sequence of characters
terminated by and including the first null character.[2]
A common misconception is
that a string is an array, because string literals are converted to arrays during the
compilation (or translation) phase. [3] It is important to remember that a string ends
at the first NUL byte. An array or string literal that contains a null character before
the last byte of the array or string literal is not a string.
http://en.wikipedia.org/wiki/C_string
y Strings and Characters
8/6/2019 MyCSC2402Notes
28/47
The values of type charare enclosed in single quotes, ie H
Strings are essentially vectors of characters. Strings are enclosed in double quotes.
ie. stringgreeting = Hello
coutgreeting[3]; //This gives the character l
Note: An individual character can be stored in one byte. A string, even if it has a
length of 1, needs to store both the contents and the length, which requires several
bytes.
y Converting Charactersto Uppercase
The toupperfunction is defined in the cctype header. It converts lowercase
characters to uppercase.
ie.
cout toupper(h); //This gives the character H
y Array
Arrays, like vectors, is also a collection of elements of the same type. But are of a
lower level.
Syntax
type_name variable_name[size];
eg.
int scores[20];
An array can also be initialized as it is declared.
int scores[] = {20, 30, 12, 5, 61};
Note that when you supply initialization values, you dont need to specify the array
size. The compiler determines the size by counting the values.
Unlike a vector, an array can never change size. You cannot usepush_backfunction
to add more elements to it. Furthermore, the size of the array has to be known whenthe program is compiled. That is, you cant ask the user how many elements are
needed and then allocate a sufficient number, as you would with a vector.
You must also keep a companion variable that counts how many elements are
actually used.
8/6/2019 MyCSC2402Notes
29/47
Array assignments are INVALID, ie. array1 = array2; is a compilation ERROR.
Also, only constants can be used to declare the size of automatic and s tatic arrays.
Not using a constant for this purpose is a compilation error.
See p.206 C++ How to Program
Note: the variable name is a pointer to the starting element ofthe array.
ie.
int a[3] = {9, 6, 8};
Here a is a pointer to the first element of the array. However, a[n] is not a pointer. It
is an identifier for the element in the array with index n.
p.322 Big C++
int a[] = {5, 8, 25};
cout
8/6/2019 MyCSC2402Notes
30/47
Unlike all other parameters, array parameters are always passed by reference. You
never use an & when defining an array parameter.
Although arrays can be function parameters, they cannot be function return types.
Also see p.217 C++ How To Program
y Character Arrays
#include
using namespace std;
int main(){char charArray[] = {'a', 'b', 'c'};
char str1[] = "abc";
char str2[] = {'a', 'b', 'c', '\0'};
cout
8/6/2019 MyCSC2402Notes
31/47
C:\Users\User\Desktop>g++ -Wall array.cpp
C:\Users\User\Desktop>a
charArray[] = abc #`
str1[] = abc
str2[] = abc
a b c ?
a b c
a b c
*/
y Cout for Arrays
Cout do not provide similar output processing capabilities for other arrays (arrays
that are not char arrays).
int a[3] = {8, 9 , 10};string b[3] = {"x", "y", "z"};
char c[3] = {'p', 'q', 'r'};
cout
8/6/2019 MyCSC2402Notes
32/47
H
p.327 - 328 Big C++
y c_str()
String object is different to string literal and string literal is different to character
array.
A character array is an array of characters.
A string literal is a null terminated array of characters.
String object is not just a null terminated character array, it is an object. It can
be thought of a class containing the null terminated array with member
functions. Member functions can be applied on the string object.
The member function c_str() turns a string object into char* pointer to the
first character in the null terminated character array.
y string(pointer to first element of a character array)
This converts the pointer to a string object.
y Looking at c_str and string(charArray_pointer) .
Letptrbe a pointer to the first element of a character array.Let strbe a string object.
See p.328 Big C++
y strcpy(charArray_pointer1, charArray_pointer2)
y strlen(charArray_pointer)
8/6/2019 MyCSC2402Notes
33/47
use #include
y Lvalues and Rvalues
Expressions that refer to memory locations are called l-value expressions. An l-
value represents a storage regions locator value, or a left value, implying that it
can appear on the left of the equal sign ( =). L-values are often identifiers.
All l-values are r-values but not all r -values are l-values.
http://msdn.microsoft.com/en-us/library/aa266358%28v=vs.60%29.aspx
y Vectors and Arrays Difference
In C++, arrays are contiguous pieces of memory. They are somewhat like blocks aligned
together, each block is then given a number, and to look at the contents of each block
one only has to supply the number of the block. All the elements of an array must be of
the same type.
A vector is similar to a dynamically allocated array but with the ability to resize itself, and
without the need for manual deallocation of memory.
http://en.wikipedia.org/wiki/Vector_%28C%2B%2B%29
READ CHAPTER 7
---------------------
y Derived Class
Derived Class Definition
class DerivedClassName : public BaseClassName{
public:
private:
8/6/2019 MyCSC2402Notes
34/47
};
All member functions and data member of the base class are automatically inherited
by the Derived Class.
It is important to note that private data members of the base class are present in
each derived-class object, but they are not accessible by member fu nctions of the
derived class. Since these fields are private data of the base class, only the base class
has access to them. The derived class has no more access rights than any other class.
Note: Forgetting the keywordpublic when defining the derived cl ass will cause
everything in the base class to beprivate.
Derived ClassConstructor Syntax
DerivedClassNameDerivedClassName(expressions) : BaseClassName(expressions){
statements;
}
Note: if you omit the base -class constructor, then the base object is constructed with
the default constructor of the base class. p.350 Big C++
y Assigning Derived Class objectto Base Class object
We can assign a derived class object to a base class object .
ie. baseClassObject = derivedClassObject;
However, all derived-class information is lost in the process, that is simply sliced
away. p.357 Big C++
When converting a derived class object to a base class, the derived class data issliced away. p.357 Big C++
Note we cannot assign a base class object into a derived class variable. p.363 Big C++
y Assigning Derived Class pointer to a Base-Class pointer
8/6/2019 MyCSC2402Notes
35/47
Assigning a derived class pointer to a base class pointer is perfectly legal. The reverse
assignment - from a base class pointer to a derived class pointer is an error. p.358
Big C++
Note: a pointer is the starting address of an object, therefore pointers to both base
and derived class objects should be the same size. p.358 Big C++
y Virtual
The virtualkeyword must be used in the base class. All functions with the same
name and parameter types in derived classes are then automatically virtual.
However, it is considered good taste to supply the virtualkeyword for the derived-
class functions as well. p.359 Big C++
You do NOT supply the keyword virtualin the function definitions. p.359 Big C++
Whenever a virtual function is called, the compiler determines the type of the
implicit parameter in the particular call at run time. The appropriate function for thatobject is then called. p.360 Big C++
Only member functions can be virtual. p.360 Big C++
class ClassName{
..
virtual return_typefunction_name(parameter, );
..
};
y C++Standard Library
C++Standard Library is a collection ofclasses and functions. The C++ Standard
Library is divided into many portions, each with its own header file. Each portion cancontain more than one class. The header files contain the function prototypes for
the related functions that form each portion of
the library. The header files also contain definitions of various class types and
functions, as well as constants needed by those functions.
(Note: each portion of the standard library is also called the library by some people,
as seen in the next section), See Small C++ How to program p.154
8/6/2019 MyCSC2402Notes
36/47
C++Standard Library
y ios
y iostream
y iomanip
y fstream
y sstream
Standard Template Library
y vector
y deque
y list
y map
y set
y stack
y queue
y bitset
y algorithm
y functional
y iterator
C++0x
y unordered_map
y unordered_set
CStandard Library (these are the
equivalentsto those ofthe Cstandard
library,their .h versions are still
acceptable)
y cassert
y cctype
y cerrno
y climits
y clocale
y cmath
Cstandard library
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
y
8/6/2019 MyCSC2402Notes
37/47
8/6/2019 MyCSC2402Notes
38/47
y fstream (header file)
fstream is one of the Standard C++ library header files.
http://msdn.microsoft.com/en-us/library/a7tkse1h(v=VS.80).aspx
The following class declarations are found in the fstreamheader file:
filebuf,fstreabase, ifstream, ofstream,fstream THESE ARE CLASSES
[Note thatfstream can mean the header file or the class depending on the context .]
http://cpp.comsci.us/etymology/include/fstream.html#class
Thefstreamlibrary defines stream class types ifstream, ofstream, andfstream. Classifstream is derived from the class istream.
http://www.adiwebs.com/use-of-fstream-library-in-c/
The ifstream class derves from the istream class.
See p.379 Big C++
-------------------------------------------------------------
An istream is a source of bytes.
An ostream is a destination of bytes. p.379 - 380 Big C++
y Hierarchy ofStream Classes
istream
header: iostream
operators: get,getline, and
variables: cin
ostream
header: iostream
operators:put, write, and
variables: cout, cerr, clog
istringstream
header: sstream
ifstream
header: fstream
iostream
header: iostream
ofstream
jeader: fstream
ostringstream
header: sstream
8/6/2019 MyCSC2402Notes
39/47
Note: open function is a member of ifstream class NOT istream class.
SCREEN
(require header:
iostream)
FILE
(require header: fstream)
STRING
(require header: sstream)
cin
cout
ifstream cinfile; cinfile.open(file.dat);
ofstream coutfile; coutfile.open(file.dat);
istringstream cinstring(str);
ostringstream coutstring;
cin x;
couty;
cinfile x; //Read a word
coutfile y;
getline(cinfile, s); //Read a line
charch;
cinfile.get(ch); //Read a character
cinfile.unget(); //Unget a character
coutfile.put(ch); //To write a single character
cinfile.close();
coutfile.close();
cinstring x;
coutstring y;
coutstring.str(); //to retrieve the
string
Note:string something;
something string;
Note .open() takes a character pointer.
We can use the c_str() function to convert a string into a character pointer. ie.
string.c_str();
8/6/2019 MyCSC2402Notes
40/47
.get(ch) is a member function of the base class istream. It removes one character
from the stream. See p.377 Big C++
A file variable must be pass by reference. See p.378 Big C++
---------------------------------------
y Stream Manipulators
library: include
We have setw, setfill, setprecision,fixed, left, right.
All are sticky EXCEPT setw.
Also by default: we have setfill( ), that is, by default the space is the fill character.
Also by default, we have alignment to the right.
y Command Line Arguments
In the command line:
prog -v input.dat
Source code
int main(int argc, char* argv[]){
}
Note that:
string(argv[0]); //gives the string prog
string(argv[1]); //gives the string -v
string(argv[2]); //gives the string input.dat
8/6/2019 MyCSC2402Notes
41/47
8/6/2019 MyCSC2402Notes
42/47
y Rando
Access
In a data file the ne linecharacter \n c nts as two characters in a .dat file.
(Confirmed by myself)
Only dis
files
ort random access thecin and cou streams which are attached
to the keyboard and the terminal, do not. ach disk file has two s ecial positions the
getposition and theputposition.
Get position
At first, the get position is at thestart position.
ut position
At first, the put position is at thestart position.------------------
fstrea fs;
fs.open test.dat);
To mo
e the get o put positions:
fs.seekg(n iosbeg); OR fs.seekg(n iosend);
fs.seekp(n iosbeg); OR fs.seekp(n iosend);
Note heren is the number ofspaces away from thestart or end position.
ie. if we would like it to move onespace to the right, makene ! ual to 1.
-----------------
8/6/2019 MyCSC2402Notes
43/47
To find the get or put :
fs.tellg();
fs.tellp();
These two functions returns the number of spaces after the start position.
ie. if the get or put is at 4, the returned value will be 1.
y Operator Overloading
The programmer is permitted to define new meanings for operators only if at least
one argument has a class type. A programmer cannot, for example, change the
meaning of the addition operator when it is used with integer arguments.
The language has a predefined set of operators, and the user is not allowed to create
new ones.
In addition, the precedence and associativity among operators is fixed by thelanguage and cannot be changed.
Also, with the exception of the function call operator, the number of arguments
required for each operator is fixed and cannot be changed.
8/6/2019 MyCSC2402Notes
44/47
Operator Function Declaration
return_type operatoroperator_symbol(parameters);
Operator Function Definition
return_type operatoroperator_symbol(parameters){
}
Operator Member Function Declaration
class ClassName{
..
return_type operatoroperator_symbol(parameters);
..
};
Operator Member Function Definition
return_type ClassNameoperatoroperator_symbol(parameters){
..
}
Note:
Nonmember Function version : implicit type conversion will be performed for both
left and right arguments.
Member Function version : implicit type conversion for the right argument only.
See p.550 Big C++
Note:
There are two categories of type conversions to consider for overloaded operators.
1) Conversion of a type to the new user -defined class. Conversion of this type is
handled using constructors. If we do not want a constructor to be used for
implicit conversion, add the keyword explicit in front of the prototype of the
constructor in the class definition.
2) Conversion from the user-defined class to another type. Conversion of thistype is accomplished by a conversion operator, which uses a type as the
operator name.
ie. ClassNameoperatortype_name(){
..
}
8/6/2019 MyCSC2402Notes
45/47
The conversion operator uses type as the operator name, has no arguments,
and does not specify a result type (since the result type is implicit in the
name).
y AssignmentOperator
The assignment operator is automatically generated when a class is created, should
the programmer not override it. The default implementation will assign all data
fields, a process termed a member-wise assignment. This is normally what we want.
See p.568 Big C++
However, operators +=, *=, and the like are NOT automatically generated.
-------------------------
y exit(1);
exitbelongs to #include . It terminates the program like assert(). However, it
does NOT print statements like assert(). Also exitreturns a value.
See p.671 Big C++
y Exceptions
logic_erroris a standard exception class that is declared in the #include .
y Throwing an Exception
throw expression;
eg.
(1)
logic_error description(reason); //initialize a logic_error object called descriptionthrow description;
(2)
throw logic_error(reason);
The keyword throwindicates that the function exits immediately. It then searches
the caller, the callers caller, and so forth, for a handler that specifies how to handle
the error.
8/6/2019 MyCSC2402Notes
46/47
y Catching Exceptions
try{
codes
}
catch(type_name variable_name){
statements
}
catch(type_name variable_name){
statements
}
If any function in the tryclause throws an exception, or call another function that
throws an exception. The search process described above for a handler begins.
We must be careful when trying to catch the exception thrown. Note that implicit
conversion, such as from intto double, or from char* to string, are not performed
when trying to catch a thrown exception.
ie.
reason cannot be catch by catch(string e).
char* cannot be catch by catch(string e).
y Throw user-defined objects
class my_error
public:
my_error(string reason);
};
my_errormy_error(string reason) : logic_error(reason){}
8/6/2019 MyCSC2402Notes
47/47
y REVISIONEXERCISES
HAVE TO READ 2D ARRAY AND POINTERS TO FUNCTION
Exercise 2
division by 0, produces a run -time error. Q17
A C-string (that is, a null terminated character array) contains a null character
at the end. But the function strlen(s) will find the length without the null
character.
Exercise 7
dereferencing a NULL pointer will cause the program to crash, but the
program still compiles. Q1
dereferencing an uninitialized pointer or a deleted pointer is just a logic error
(run-time error), the program still compiles and DOES NOT crash.
coutNULL; will display 0 as NULL is converted to zero. Q14
int a[3] = {5, 6, 9};
int* ptr = a;
cout