Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Oxford University
Computing Services
How to Use this User Guide
This handbook accompanies the taught sessions for the course. Each
section contains a brief overview of a topic for your reference and
then one or more exercises.
Exercises are arranged as follows:
A title and brief overview of the tasks to be carried out;
A numbered set of tasks, together with a brief description of each;
A numbered set of detailed steps that will achieve each task.
Some exercises, particularly those within the same section, assume that
you have completed earlier exercises. Your teacher will direct you to
the location of files that are needed for the exercises. If you have any
problems with the text or the exercises, please ask the teacher or one
of the demonstrators for help.
A number of conventions are used to help you to be clear about what you
need to do in each step of a task.
In general, the word press indicates you need to press a key on the
keyboard. Click, choose or select refer to using the mouse and
clicking on items on the screen.
Names of keys on the keyboard are enclosed in angle brackets; for
example <ENTER> represents the Enter (or Return) key.
Multiple key names enclosed in angle brackets and linked by a + (for
example, <CTRL+Z>) indicate that the first key should be held down
while the remaining keys are pressed; all keys can then be released
together.
Where two or more keys are each enclosed in separate angle brackets (for
example, <HOME><HOME><UP ARROW>) each key in the sequence
should be pressed in turn.
Words and commands typed in by the user are shown like this.
Labels and titles on the screen and button names are shown l i k e t h i s .
Drop-down menu options are indicated by the name of the option
enclosed in square brackets, for example F i l e | P r i n t . To select the
option P r i n t from the F i l e menu: click with the mouse button on the
F i l e menu name; move the cursor to P r i n t ; when P r i n t is
highlighted, click the mouse button again.
A button to be clicked will look l i k e t h i s .
The names of software packages are identified like this, and the names of
files to be used l i k e t h i s .
Revision Information
Copyright
The copyright of this document lies with Oxford University Computing Services.
2 THINGS TO UNDERSTAND......................................................................................3
2.1. Compilers, new and old...................................................................................................................................3
4.2. Dev-C++............................................................................................................................................................5
Exercise 1 Installing Dev-C++.......................................................................................................................6
5.6. Characters.......................................................................................................................................................30
5.7. Strings.............................................................................................................................................................31
5.8. Casts................................................................................................................................................................32
Exercise 4 Create additional projects...........................................................................................................34
6 INTRODUCTION TO FUNCTIONS..........................................................................37
6.1. Creating a function........................................................................................................................................37
Exercise 5 Examining a function.................................................................................................................38
7.4. Constructors...................................................................................................................................................53
Exercise 12 Using constructors......................................................................................................................54
7.5. Destructors......................................................................................................................................................55
10 MORE ON FUNCTIONS........................................................................................98
10.1. Multiple arguments and default values......................................................................................................98
Exercise 27 Functions with multiple arguments and default values..............................................................98
11 POINTERS...........................................................................................................115
11.1. Initialising pointers.....................................................................................................................................115
Exercise 34 Using pointers...........................................................................................................................116
13 SESSION 2..........................................................................................................125
13.1. files used......................................................................................................................................................125
15 MORE ON CLASSES..........................................................................................135
15.9. Composition................................................................................................................................................156
Exercise 50 Composition, using objects as members of other classes.........................................................156
Exercise 51 Composition, dates as object members of student class...........................................................160
Exercise 52 Composition, Starting the OUCS ATM....................................................................................161
16 OPERATOR OVERLOADING.............................................................................162
16.1. Overload + operator...................................................................................................................................162
Exercise 53 Overloading the addition operator +........................................................................................162
19 POLYMORPHISM................................................................................................179
19.1. Polymorphism.............................................................................................................................................180
20 SESSION 3..........................................................................................................187
20.1. files used......................................................................................................................................................187
21 ABSTRACT CLASSES........................................................................................188
21.1. Examining an Abstract Class....................................................................................................................189
Exercise 63 Abstract classes & dynamic binding........................................................................................189
Exercise 64 Create a new Abstract class......................................................................................................193
Exercise 65 ATM, base class pointers and private utility functions............................................................194
23.3. Algorithms...................................................................................................................................................201
24 APPENDIX...........................................................................................................240
24.1. Arithmetical Operators..............................................................................................................................240
24.10. Scope..........................................................................................................................................................244
24.12. Constants...................................................................................................................................................244
1 Introduction
Welcome to the C++ for Physics course.
This booklet accompanies the course delivered by Oxford University Computing
Services (OUCS), IT Learning Programme. Although the exercises are clearly
explained so that you can work through them yourselves, you will find that it will
help if you also attend the taught session where you can get advice from the
teachers, demonstrators and even each other!
If at any time you are not clear about any aspect of the course, please make sure
you ask your teacher or demonstrator for some help. If you are away from the
class, you can get help by email from your teacher or from help@oucs.ox.ac.uk.
Polymorphism;
Virtual member functions;
Pure virtual member
functions;
Abstract classes;
2 Things to understand
4.2. Dev-C++
What is Dev-C++? Dev-C++ is a freely available C++ compiler.
One thing is for sure, we speak a different language from computers and there is
no way a computer cannot understand the spoken or written language we use in
our daily conversations. To make matters worse we do not understand the binary
language that our computers use to perform complicated tasks. This suggests we
have a communication problem.
So what is a compiler and how can it help? The compiler is a tool that allows us
to write instructions in some specially defined language (unfortunately not
English, yet) in our case C++, which us humans can understand. This is called
the s o u r c e code (a high level language code). The compiler then converts this
precise language (C++) into a concise language that the computer can understand
called o b j e c t code (a low level language code). This object code will most likely
be used by other programs in the process of creating a working program.
Task 1 Step 1
Install Dev-C++ Using Windows Explorer or My Computer navigate to
the H : \ d r i v e and double click on the program
d e v c p p - 4 . 9 . 9 . 2 _ s e t u p . e x e , see Figure 1.
Figure 1
Step 2
Figure 2
Step 3
Figure 3
Step 4
Click the I A g r e e button when you get to the License
Agreement window, see Figure 4.
Figure 4
Step 5
Click on N e x t when you see the Choose Components
window, see Figure 5.
Figure 5
Step 6
Click the I n s t a l l button at the Choose Install
Location window. See Figure 6.
Figure 6
Step 7
Click on the Y e s button at the prompt shown in
Figure 7.
Figure 7
Step 8
To complete the installation click F i n i s h , see Figure
8.
Figure 8
Step 9
At the Beta version Notice click O K , see Figure 9
Figure 9
Step 10
When you see the D e v - C + + f i r s t t i m e
c o n f i g u r a t i o n window (Figure 10) click the
> N e x t button.
Figure 10
Step 11
Make sure Y e s , I w a n t t o u s e t h i s f e a t u r e is
selected then select the > N e x t button to select
additional features, see Figure 11.
Figure 11
Step 12
To create the code completion cache click the
> N e x t button, see Figure 12.
Figure 12
Step 13
Dev-C++ should now be successfully configured, see
Figure 13. If you do NOT see this window, speak to
the teacher or one of the demonstrators. Select O K .
Figure 13
Step 14
Close the T i p o f t h e d a y window by clicking the
C l o s e button, see Figure 14.
Figure 14
Step 15
Dev-C++ installation has finished and you are now
ready to write you first program. Instructions on how
to do this are in Section 5.2
Figure 15
Task 1 Step 1
Launch eclipse OSX machines, select the "l a u n c h p a d " from the
taskbar
Step 2
Figure 16
Figure 17
Step 1
Task 2
Choose a workspace Choose a new workspace
Figure 18
Task 3
Download the Step 1
materials for the
session from the web. Download the required materials from the web.
These are currently These are located at
located at:
Part 1: http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013
/EclipseStudentFiles_part1.tgz
Part 2: http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013
/EclipseStudentFiles_part2.tgz
Part 3: http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus
_2013/EclipseStudentFiles_part3.tgz
Task 4
Import the first part into Import the project skeletons into your
your project workspace workspace
Select F i l e = > I m p o r t
Figure 19
Figure 20
Figure 21
Figure 22
Task 8
To run the project, and
for each subsequent
build + run cycle, just See Error: Reference source not found on the next page
select the green play
button.
See Error: Reference
source not found on
the next page
Figure 23
Task 1 Step 1
Create your first If Dev-C++ is not already running, open the program
program.
by double clicking on the icon in the N A L
window or select S t a r t | A l l P r o g r a m s |
Bloodshed Dev-C++ | Dev-C++ .
Figure 24
Select C o n s o l e A p p l i c a t i o n
Add a project the name of W e l c o m e
Select the C + + P r o j e c t radio button
Click O K
Save the project to the \ as W e l c o m e . d e v see
Figure 25
Figure 25
Figure 26
Task 2 Step 1
To create a new project,
select File=> new =>
"C++ project"
Figure 27
Task 3
Create a new empty Step 1
project Select an empty project using the “Mac OSX GCC"
toolchain on the Mac or the “Linux GCC toolchain”
on Linux
Step 2
Give the project the name H e l l o and accept the
default options
Figure 28
Figure 29
Task 5
Create an initial program Copy the following text into your new source file:
to pring “Hello World” to
the console. #include <cstdlib>
#include <iostream>
Figure 30
Task 7
To run the project, and
for each subsequent
build + run cycle, just See Error: Reference source not found in Error: Reference
select the green play source not found
button.
See Error: Reference
source not found
#include <iostream>
Notifying the pre-processor to include in the program the contents of the header
file i o s t r e a m before compilation. This file must be included for any program
that outputs data to the screen or inputs data from the keyboard
In the programs we will be creating in this session we will not be using the
arguments a r g c and * a r g v [ ] and the statement i n t m a i n ( i n t a r g c , c h a r
* a r g v [ ] ) ; could be replaced with i n t m a i n () .
Task 1 Step 1
Modify the program Add the following statements immediately above the
statement r e t u r n E X I T _ S U C C E S S ;
int anum = 0;
cin >>anum;
Step 1
Save the file as m a i n . c p p
Task 3 Step 1
Compile the program Build the project
If you have any errors in the code the line containing
the error will be highlighted. Correct any errors and
compile the program again. Repeat as necessary.
Task 4 Step 1
Run the program Run the project and select the box in Eclipse labelled
“C o n s o l e ” as in Figure 31.
Enter a number at the prompt and press E n t e r
Figure 31
Figure 32
Table 2 shows how you would declare and initialise four other data types for use
in programs.
Table 2
5.6. Characters
Characters are normally stored in variables of type char, but can also be stored
as i n t e g e r data types. Characters are represented as single byte integers in the
computer so it is possible to output a character as an integer or as a character.
All characters have a numerical representation in the computer and the ASCII
(American Standard Code for Information Interchange) character set shows each
character and its decimal equivalent. See appendix Error: Reference source not
found.
Note: After entering a character the <ENTER>key must be pressed before the
number is read by the program. To ensure the <ENTER> key press is ignored in
the program add the statement:
cin.ignore(); cin.ignore() is a function that reads and discards a character, in
this case the <ENTER> key press.
The following four statements correctly declare a variable of type char, output a
user prompt, then read a character and store it in the variable aChar. The enter
key press is then ignored.
char aChar;
cout << "Enter the CHARACTER A: " ;
cin >> aChar;
cin.ignore();
Characters can also be read into a program and stored as integers. The statement
bInt = cin.get(); uses the cin.get() function to read one character from the
keyboard and store it in integer variable bInt. The integer variable can then be
cast to a character, see section 5.8 C a s t s .
5.7. Strings
Next to numbers, strings are the most commonly used data type in
programming.
A string is a sequence of characters such as “O x f o r d ” or “S t . A n d r e w s ”. In C++
strings are enclosed in quotes. The quotes are not part of the string, they identify
the data type as a string.
To use the string type in your programs add the header file #include <string>
at the top of your program. This allows the use of part of the C++ library of
classes, the string class and its member functions.
The four statements below allow you to declare a string, read the string in and
output to the screen
string name;
cout << "Enter your name ";
cin >> name;
cout <<"You say your name is: " <<name <<endl;
Note: When reading in a string with a space such as “Ann Black” only the first
name is read into n a m e . You could create a second string and get the user to
enter B l a c k but this is inconvenient. To handle this situation use the
getline(cin, name); command instead of cin >> name;. This reads all key
strokes into n a m e until the <ENTER> key is pressed. The g e t l i n e function (more
on functions later) creates a string containing all of the characters from the input.
The string class has many useful functions you can use to manipulate strings. An
example is the length() member function.
See Appendix 24.16 for more information on the string class and member
functions.
5.8. Casts
When you need to represent a value as a different type you can use the
s t a t i c _ c a s t notation as shown here:
int anInt;
anInt = static_cast<int>(doubResult); where d o u b R e s u l t is a double.
Legacy code may use the following notation to cast different data types:
char aChar;
aChar = static_cast<char>(bInt); Where b I n t is an integer.
Task 3
Modify your program in
T a s k 2 to read in two
characters. Enter the
characters “a ” and “Z ”.
Output the two
characters with the
character case changed.
i.e. “a ” becomes “A ” and
“Z ” becomes “z ”.
You will need to look at
the Appendix 24 to
establish the A S C I I
integer values of each
character.
Task 4
Create another project
called A d d r e s s .
Write a program that can
be used to collect user
data.
Output this data to
screen as shown in
Figure 33.
Figure 33
Task 5
Create another project
call it C a l c A r e a .
Write a program to
calculate the area of a
circle for different
radius.
Extend the program to
calculate the
circumference.
Extend it again to read
in the height of a
cylinder and calculate its
volume.
∏ = 3.141592
a = ∏r2, c= 2∏r, v=
ah
Task 6
Create another project
call it CtoF.
The program will
prompt the user to enter
a temperature in
centigrade. The
program will calculate
the equivalent
temperature in
Fahrenheit and output
this to screen. The
formula is Fahrenheit
= 1.8 * Celsius +
32;
Task 7
Create a new project, call
it S e a r c h S t r i n g .
The program will display
a string of text to the
user.
The user will then be
prompted to select a
word from the sentence
then input a replacement
word. See section 24.16.
Figure 34
The string before and
after the update should
be displayed as in
Figure 34.
6 Introduction to Functions
Functions are used to encapsulate a set of operations and return information to
the main program or calling routine. E n c a p s u l a t i o n is data, information or
detail hiding.
Once a function is written, the detail of how it works is not important. It is only
necessary to understand what data input the function needs (its parameters) and
what output is produced.
The use of functions provides several benefits. It makes programs significantly
easier to understand and maintain. The main program function can consist of a
series of function calls rather than hundreds of lines of code. A second benefit is
that well written functions can be reused in multiple programs.
A function is d e c l a r e d with a p r o t o t y p e early in the program. A function
prototype consists of the r e t u r n t y p e , a f u n c t i o n n a m e and a p a r a m e t e r l i s t
indicating the data the function will receive. The function prototype is also called
the function d e c l a r a t i o n .
The function d e f i n i t i o n consists of the prototype and a function body, which is a
block of code enclosed in parenthesis.
Using a p r o t o t y p e is a way of telling the compiler the data types of any return
value and of any parameters being passed, to enable error checking to be done.
The d e f i n i t i o n creates the actual function in memory.
Arguments can be passed to functions in two ways. P a s s - b y - v a l u e is where a
copy of the argument value in the main program is made and then passed to the
function. The copy in the function only exists in memory as long as the function
is active. When the code within function has been run the memory is released
and the value held there lost. Changes to the copy of the variable in the function
do not affect the original variables value.
Arguments can also be p a s s e d - b y - r e f e r e n c e . When arguments are passed in
this way any changes made to the arguments in the function are reflected by
corresponding changes to that data variable in the calling part of the program.
Pass-by-reference is good for performance reasons because it can eliminate the
pass-by-value overhead of copying large amounts of data. In later sections we
will examine how p o i n t e r s can be used to p a s s - b y - r e f e r e n c e .
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project
Run the program entering the data as requested. The
CharNumStringFunc
output should be the same as Figure 35.
Figure 35
Step 2
Examine the following statements. Only the
important parts of the program are explained, the rest
has been covered in previous exercises.
All functions must be declared prior to use and there
are four p r o t o t y p e s in this program. Creating
prototypes allows the compiler to perform t y p e
checking on the arguments to ensure the input data is
the correct type before processing it.
Calling functions:
readChar(); This is a function call to the
r e a d C h a r ( ) function. Notice no parameters are
passed. The function must therefore contain the code
to read in and output the user input.
cout <<passStringRetInt()<<endl<<endl;
Function Definitions:
void readChar() { }
This is the function definition for readChar(). The
code within the braces is used to read in a character
and output the value to screen.
int passStringRetInt()
{ }
The user enters a string in the function. The number
of characters in the string is established using string
class member function l e n g t h ( ) . This is returned to
the calling statement.
void readDouble()
{
static int aNum = 1;
aNum +=1;
}
N o t e here the use of the keyword s t a t i c . This has
defined the memory location a N u m as static and this
cannot change.
Memory is normally allocated to function variables as
the functions are called. When the function call is
complete the memory allocated is released and all
data in the function variables lost.
Using the keyword s t a t i c means memory is allocated
from a different part of memory and value in the
variable is maintained throughout the life of the
program.
The statement aNum +=1; increments the static
variable by 1 each time the function is called using the
assignment operator + = . In this example 1 is being
a d d e d to the variable a N u m .
Task 2
Remove the key word
s t a t i c from the
declaration static i n t
aNum = 1;
this is in the v o i d
r e a d D o u b l e ( ) function.
Compile and run the
program and see how the
program responds.
Task 1 Step 1
Open the project E v e n Read two integers in to m a i n ( ) and pass them to a
you created in Section 4, function. The prototype is void intCalcs(int,
Exercise 4 and change int);
the structure of the i n t C a l c s ( ) function should calculate and display the
program to make use of result of the division and modulus of the two variables
functions. passed, see Figure 36.
Read in two doubles to variables in m a i n ( ) . Pass the
two doubles and the value of one integer to the second
function, the prototype is i n t C a l c s ( d o u b l e ,
double, int);
Within function C a l c s ( ) write statements to produce
the output as shown in Figure 36.
Most of the code already exists within m a i n ( ) .
Return the result of the multiplication of one double
and an integer, cast this value as an integer.
Display the returned value within m a i n ( ) , as shown
in the second last line in Figure 36.
Figure 36
Task 2
Create a separate
function to change the
character case of two
characters. The
characters should be
passed from m a i n ( ) to
the function and the
results of the changes
displayed from within
the function.
Task 3
Create a new project, call
it C h u r c h H e i g h t .
Write a program that
will calculate the height
of a building given the
following information.
You are 2 7 0 metres
away from a church. The
angle from your feet to
the top of the church is
1 6 degrees, see Figure
37 and Figure 38.
The height of the Figure 37
building can be
calculated using the
formula:
tan(angle) = length
of opposite side/
length of the
adjacent side.
radians =
degrees*∏/180.
The program should
contain at least two
functions to calculate the
height of the building.
You will need to convert Figure 38
the angle to radians
before using the c m a t h
function t a n ( x ) . See
Appendix 24.15 for more
information on c m a t h
functions.
Remember to include
the header file < c m a t h >
in your program.
Task 4
Create a new project, call
it M e t r e s .
Write a function named
F I t o M e t e r s which takes
two double parameters,
a number of feet and a
number of inches and
returns a double number
of equivalent meters.
Assume there are 2.54
centimeters (0.0254
meters) in one inch.
Task 5
Create a new project, call
it S e c o n d s .
Two identical
experiments have been
conducted and the time
difference between the
two (in seconds) is
critical.
Write a function
(H M S e c o n d s ) that will
be called repeatedly and
will take three integer
parameters. A number
of hours, number of
minutes, and number of
seconds.
The total in seconds will
be returned to main()
and used in further
calculations to analyse
experimental results.
In the previous section when working with functions all arguments passed to the
functions were copies of variable values from m a i n ( ) . The arguments were
passed by their v a l u e .
Pass by Value is the default argument passing mechanism for C++. When a
function is passed an argument the function gets a copy of the value from the
calling function (m a i n ( ) in previous examples). This copy value remains in scope
(see section 24.10) and available until the function call has completed when the
copy in the function is destroyed.
Therefore a function that takes v a l u e -arguments cannot change the variable
passed from m a i n ( ) because any changes only apply to local copies in the
function, not the actual caller's variables.
Passing variables to functions by r e f e r e n c e is very useful when we need to
change or update variable(s) via a function.
Pass by reference involves passing an address and not a copy of the data to the
function. This is usually more efficient than passing by value because there is no
requirement to copy large parts of memory.
However, this argument passing mechanism enables a function to modify any
function arguments even if it's not supposed to. To avoid this, declare all read-
only parameters as c o n s t and pass them by reference.
The format of a function prototype when using call by reference is:
r e t u r n - d a t a - t y p e f u n c t i o n - n a m e ( r e f e r e n c e p a r a m e t e r ) . To indicate a
reference parameter, an ampersand (& ) is written in the function prototype and
header after the parameter t y p e name
The statement void squared(int &); has no return data type (v o i d ), it’s name
is s q u a r e d and it accepts a r e f e r e n c e p a r a m e t e r (& ) of type i n t (integer).
Task 1 Step 1
In eclipse, open the Compile and run the program. The output should be
project FunctionRef the same as shown in Figure 39.
Figure 39
Examine the function prototype:
void squared(int &);
This shows the function s q u a r e d accepts a
r e f e r e n c e p a r a m e t e r of type i n t . The reference
parameter is the memory a d d r e s s of the argument
passed to the function.
The function uses this address to both get and set the
value stored in variable a , (2 1 ) in m a i n ( ) . A
reference to this address is passed to the function with
the function call s q u a r e d ( a ) ;
Step 1
Examine the function v o i d s q u a r e d ( i n t & x )
x refers to the a d d r e s s of (a ) in main, that holds the
number 2 1 .
When parameters are marked as reference
parameters, the memory address of each argument is
passed to the function. The function will use these
addresses to both get and set values. The values
changed are the variables stored where the function is
called, m a i n ( ) in this example.
Task 3
Create another project
call it F u n c R e f M a r k s .
Read in the name of a
student and three exam
marks.
The marking has been
too severe in the three
exams and all students
are to receive an
additional 5 marks.
The student name has
been entered incorrectly
and needs to be changed.
Prompt the user to enter
the change in student Figure 40
name and value that
each result will be
increased by.
Making just one function
call modify the exam
results and the student
name.
All the variables should
be stored in the m a i n ( )
function. The output
should be similar to that
shown in Figure 40.
Task 4
Open the file
F u n c C o n s t R e f and
examine the program.
Compile the program
sorting any errors.
Arguments are being
passed by reference but
incorrectly, sort these
errors. There are also
some problems with the
program logic.
When the program is
compiled and run the Figure 41
output should be as
shown in Figure 41.
In the previous section we have been working with simple programs that display
messages to the user, store data input as different data types, manipulate the data
in some way and output the results to screen.
We now look at objects and classes. In the real world there are objects
everywhere, students, staff, cars, birds, houses and many more. All objects have
a t t r i b u t e s , these are similar to the variables created in previous tasks. Some
attributes of a student may be height, weight, race, course of study etc. All objects
exhibit b e h a v i o u r s or operations, cars accelerate and decelerate, students
matriculate, enrol on courses and leave university.
Now, what is the relationship between a class and an object? A good analogy
would be, from a drawing for a house it would be possible to build many houses,
and from a class it would be possible to build many objects.
If we had a student class we could create many objects from the student class to
represent the many students enrolling. Each of these objects would be uniquely
identified. They would share common attributes and exhibit common
behaviours. If we wanted an object to perform some task we would call the
appropriate member function allowing an operation to take place changing the
behaviour of that object.
Member functions are different from the functions you have created so far.
Member functions are always associated with objects and are called or invoked
with a dot notation, o b j e c t . m e m b e r f u n c t i o n n a m e ( ) . An example is
s t u d e n t 1 . g e t N a m e ( ) . The object is s t u d e n t 1 and the member function is
getName().
Member functions contain the detail of how the technical aspects of some
operation will be processed. When member functions are invoked these technical
issues are hidden from the end user. When the member function is asked to do
some operation a message is sent (a member-function call) telling the member
function of that object to perform the operation detailed in the function.
Functions are not completely new, we have had a brief introduction and you have
already created some of your own. Note also that m a i n ( ) is a function and is
called automatically when you run your programs. However, it is not a member
function as there is no object associated with it.
Task 1
Create a new project, call
it S t u d e n t . Name the
new source file
StudentUG.cpp.
From the directory
where you unpacked the
source materials, open
the file called
S t u d e n t U G . t x t . Copy
the C++ program.
Replace the default C++
template file
(S t u d e n t U G . c p p ) with
the file copied from Figure 42
StudentUG.txt.
The program should look
like Figure 42.
Compile and run the
program.
Before you can create the object m y N a m e it is necessary to define the class from
which the object will be created. The class definition is shown below.
When you use functions it is common to pass data (called parameters) to the
function. The function then manipulates the data before displaying an output
and/or returning a value.
Figure 43
The statement cout <<"Hello " << name << endl; provides the output.
Task 1
Modify the program you
created in the previous
exercise S t u d e n t U G . c p p
to read in a student name.
The name should be passed
to a member function. The
parameter should be output
from within the function to
welcome the user to C++ Figure 44
programming. The output
should be similar to Figure
44.
Task 2
Modify the program in the
above task to read in two
more names. Each name
will be for a different
student and you will need
to create additional
o b j e c t s (instances) of the
class.
Figure 45
When data members are declared as p r i v a t e the data is hidden. This is called
e n c a p s u l a t i o n and means the attributes of the object are hidden and can only
be accessed via member functions.
As there is no direct way to change a data member you will also need to create a
m e m b e r f u n c t i o n to set the data member to a value and create a second
m e m b e r f u n c t i o n to output the value held there.
Data members can also be declared p u b l i c . A data member that is declared
p u b l i c can be accessed from any (non-member) function.
A p r o t e c t e d data member can only be accessed by member functions of its own
class and by member functions of classes derived from this class. We will learn
more about derived classes and inheritance later.
Task 1
Create a new project, call it
S t u d e n t G e t S e t . Create a
new source file call it
StudentCourse.cpp.
From the directory
where you unpacked
the source materials,
open the file called Get
Set.txt.
Copy the C++ program.
Figure 46
Replace the default C++
template file
(S t u d e n t C o u r s e . c p p )
with the file copied from
GetSet.txt.
Compile and run the
program, it should look like
Figure 46. You may have to
sort some compilation
errors.
Task 2
Examine the member
function r e t u r n N a m e ( )
shown in Figure 47. This
function produces the
output but what does
g e t N a m e ( ) do?
Figure 47
Task 3
Modify the
S t u d e n t C o u r s e source
file to enable the user to
add a student name,
enrolment date and
number of years of course.
Once entered this data
should be output to screen.
Figure 48
You will need to create
additional d a t a m e m b e r s
and m e m b e r f u n c t i o n s to
achieve this.
The output should be
similar to Figure 48.
7.4. Constructors
When you create objects from the S t u d e n t C o u r s e class it is necessary to give
initial values to all the data members. If we were entering data for five people
and they were all following the same course of study it would make sense to
initialise the c o u r s e N a m e data member (it is possible to initialise some or all of
the data members) when each object is created.
A c o n s t r u c t o r is a special kind of function that must have the same name as the
class. Constructors are normally defined as p u b l i c and never have a return type.
They can be used to automatically initialise data members.
In previous programs you have written, a d e f a u l t c o n s t r u c t o r has been
provided by the compiler. However, it is not possible to pass parameters to a
default constructor function, so the data members in the programs created so far
have not been automatically initialised. To initialise these data members you
created member functions that assigned values to data members.
Although a default constructor is provided at compilation time it is a good idea to
create your own so that the data members can be initialised.
It is worth noting here that functions (constructors are functions) can be
o v e r l o a d e d . This means it is possible to have more than one function with the
same name. Note that overloaded functions (functions with the same name)
must have different types of, or number of arguments.
Constructors (functions) can also be overloaded with more than one function
with the same name but different types or number of parameters. Fortunately for
us the compiler automatically calls the correct function whose parameters match
the arguments used in the function call. There is more information on function
overloading in section 10.5.
Task 1
Create a new project, call it
C o n s t r u c t o r . Create a
new source file call it
Constructor.cpp.
From the directory
where you unpacked
the source materials,
open the file called con
structor.txt.
Copy the C++ program.
Figure 50
Replace the default C++
template file
C o n s t r u c t o r . c p p with the
file copied from
constructor.txt.
Compile and run the
program, it should look like
Figure 50. You may have to
sort some compilation
errors.
Task 2
In the constructor shown in
Figure 51 what does the
statement
setCourseName(name);
do?
Figure 51
Task 3
Create a third constructor
that will take arguments of
y e a r s and e n r o l D a t e .
Add a third object, call it
student3.
Write a statement that will
output the results of a call
to this additional
constructor.
Task 4
Each student has an I D
n u m b e r and a
supervisor.
Modify the program to
allow student I D ’ s and the
n a m e s of supervisors to be
added to each object
created.
Create member functions to
allow the user to add or
modify both the I D and
supervisor names.
Create member functions to
output these details to
screen.
7.5. Destructors
Both constructors and destructors are special class methods. We have seen how a
constructor is called whenever an object is defined.
A destructor is a method that has the class name prefixed by a tilde, ~ .
Destructors cannot return values and therefore have no return type specified.
Unlike constructors, destructors have no arguments and thus cannot be
overloaded. Overloading a function is using the same name for more than one
function provided the functions have different parameter, see section 10.5.
An object's destructor is called whenever an object goes out of scope. The
purpose of the destructor is to clean up and free any dynamically allocated
memory that the object was using and release other system resources.
In the examples used so far no destructor has been provided for any class created.
In these programs it has been unnecessary. If we do not explicitly provide a
destructor the compiler will create an empty destructor in the same way that an
empty constructor is created if one is not explicitly created.
When classes are created, any objects instantiated from them that contain
dynamically allocated memory will need destructor methods (functions) added to
implicitly free any dynamically allocated memory when the object goes out of
scope.
In the class example shown below the destructor function is ~ Staff ().
class Staff {
private:
int staffid;
double staffsal;
public:
int getID()
{return staffid;
}
double getSal()
{return staffsal;
}
}; /*end of class*/
Task 1 Step 1
Open an existing project. In eclipse, open the project Header
Create a header file and Add a new Source file to the project, F i l e | N e w |
include reference to this in Source File
the source code file. Save and name the file O x S t u d e n t s . h in the same
When m a i n ( ) is called the folder as H e a d e r .
class definition in the
header file is used to create
objects of the class defined
in the header file. Step 1
Cut the class definition code from H e a d e r . c p p file
and paste it into the O x S t u d e n t s . h file.
As you will be using input and output in the class
header file you need to include the iostream
library. Add # i n c l u d e < i o s t r e a m > , # i n c l u d e
< s t r i n g > and u s i n g n a m e s p a c e s t d ; to the top
of the header file.
Step 1
Compile the program
You should get a compilation error at line
OxStudents myName;
This is because m a i n ( ) does not know about the
header file containing the class information.
Step 1
Add the statement # i n c l u d e " O x S t u d e n t s . h "
beneath the other # i n c l u d e directives in
H e a d e r . c p p file.
Compile and run the program
The statement # i n c l u d e " O x S t u d e n t s . h "
instructs the C++ pre-processor to replace the
directive with a copy of the contents of
O x S t u d e n t s . h before the program is compiled.
With the O x S t u d e n t s class in a header file it is
now possible to include and reuse that class in any
program by just adding the appropriate header file
to m a i n ( ) .
N o t e : Header files written like this can only be
included once in a project. We want to make the
code re-usable. We get around this in 15.5
N o t e : User defined header files can be kept in the
same directory as the source code files. It is
normal to separate them in larger projects. This
requires eclipse to be configured to look in a
different directory for include files. This is out of
scope.
Task 5
Create another project call
it C o u n t r y . Modify the
m a i n ( ) source code to use
the class in the header file
#include
"OxStudents.h".
N o t e : the O x s t u d e n t s . h
file will need to be copied to
Figure 52
the C o u n t r y project folder.
The user should enter a
name and a country which
should be output to screen,
see Figure 52. Modify the
source code in main and
OxStudents.h to achieve
this.
Task 6
Open the project
C o n s t r u c t o r you created
in Exercise 12.
Create a new header file
that includes the class
definition, save this as
constructor.h.
To use the class from within
main() add #include
"constructor.h" at the
top of the program where
the other header files are
included.
Test the program.
Task 7
OPTIONAL
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
p r o j e c t I f . There is
one . c p p file and one . h Run the program. The output should be the same as
header file. Figure 54.
Figure 54
Step 1
Examine the v o i d g e t G r a d e s ( ) member function in
the S t u d e n t M a r k s I n t e r f a c e . h file.
The if single selection statement performs only one
action when the condition tested ( E x a m 1 > = 9 0 ) i s
true.
if(Exam1 >= 90)
cout<< "the Exam1 grade is 'A'" <<endl;
Figure 55
The appropriate grade is selected and user prompted
of the result from within g e t G r a d e s ( ) member
function.
Task 4
A second student has
just joined the class.
Modify your program so
the user is prompted to
add details for a second
student and their results
for the four exams.
Modify the code so the
user is prompted to add
a Course Name.
Output the results to Figure 56
screen. They should
look similar to Figure 56.
Task 1
In eclipse, open the Compile the program, sorting any compilation errors.
project IfSwitch. Run the program. The output should be the same as
There are two files, one Figure 57.
. c p p files and one . h
header file.
Figure 57
Task 2 Step 1
To see how the s w i t c h Examine the v o i d g e t G r a d e s ( ) member function in
statement gets its the S t u d e n t M a r k s I n t e r f a c e . h file, see Figure 58.
parameters and to
understand how
characters can be used in The use of the i f statement was explained in the last
a s w i t c h statement. exercise. The statement c o u n t G r a d e s ( ‘ A ’ ) is new.
It is calling the function c o u n t G r a d e s and passing a
character parameter ‘A ’ as the student achieved > =
90 marks.
Figure 58
Step 1
Exam the code in c o u n t G r a d e s member function.
See Figure 59
Figure 59
Task 4 Step 1
Exam how the count of Examine the member function o u t P u t G r a d e s ( )
grades is output. shown in Figure 60
Figure 60
This member function outputs the object member
variables a C o u n t . . . f C o u n t . The statement
s t u d e n t 1 . o u t P u t G r a d e s ( ) ; in m a i n ( ) is used to
call the member function and output the total of each
grade achieved by the object s t u d e n t 1 .
Task 5 Step 1
Create a new Write a program that reads a product ID (Product 1 -
project, call it Electr 4 ) and the q u a n t i t y required.
onicsOutlet.
A s w i t c h statement should be used to determine the
You sell the following product sold.
four products at the unit
price shown. Items that are sold in quantities > 9 9 units are
reduced in price by 10% before tax is applied.
Product 1:Astable
multivibrators The output should show the cost per item, the VAT
@£15.45 element and the total cost including VAT at 17.5% as
shown in Figure 61.
Product
2:Integrated-Circuit
Timers @ £21.78.
Product 3:ECL
@£15.78.
Product 4:BiCMOS
digital circuits
@£34.99.
Figure 61
N o t e : Use a class file (header file).
Create a default constructor to initialise all data
members.
Initialise the product ID, the Unit Cost and the
product name in the switch statement. To do this you
will need to overload the default constructor.
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
p r o j e c t W h i l e . There
is one . c p p file and one Run the program. The output should be the same as
. h header file.
Figure 62.
Figure 62
Task 4
Modify the program in
the task above to read in
the results of tests for
two students. Each
student has taken 4
tests. Output the total,
average, highest and
lowest scores for each
student.
N o t e : you will need to
use a method of
selection to establish the
highest and lowest
marks inside the while
loop.
Task 5
Create a new
project, call it BMI.
The program should
calculate the body mass
index (BMI) of a person
where their height is in
feet and inches and their
weight is in stones and
pounds.
BMI =
weight(kg)/height(m)2
Task 6
OPTIONAL
Create a new
project, call it
avgTemp.
Seven temperature
readings are taken at
each of three locations in
Oxfordshire and stored.
Create a temperature
class to accept the
temperature readings
and other details for each
location.
Task 7
OPTIONAL
Using the output shown
in Figure 65 write a
program that will output
this display.
Create a class file that
can be used to display
this detail. The program
does not have to be
functional other than to
display this screen and
verify the account and Figure 65
PIN numbers.
Figure 66
Figure 66 shows the code required to read in four
exam marks.
N o t e : The integer i used to control the loop and has
been declared within the brackets of the f o r loop (i n t
i = 0 ; ). This means that i only exists within the loop.
When the loop ends, i ceases to exist. This is called
the s c o p e of the identifier.
See appendix Scope 24.10 for more information.
Task 2
OPTIONAL
Create a new
project, call it Books
.
The program should
create three instances of
a class called B o o k s .
Create each of the
objects inside a f o r
loop.
Create member
functions to add a Title,
Author and date of
publication.
Output the details of the
three books to screen.
Task 1 Step 1
Note: You should Open D o W h i l e project
complete the chapter on
Run the program entering the numbers 19, -19, 19, -19
classes before
when prompted
attempting this task.
The output of the program is shown in Figure 67.
In eclipse, open the
project DoWhile.
Establish how the do…
while loop can effect a
program written to
verify user input.
Figure 67
Establish why when using the d o … w h i l e loop for
repetition a negative value (-19 as shown in Figure 67)
is established as being greater than zero.
H i n t : Look at where in the block the condition is
tested.
Task 2
Note, you do not need
the classes chapter to
attempt this exercise.
Create a new
project, call it Factor
ial
Using different
repetition statements
write a program to
calculate and display the Figure 68
factorial of a value
entered by the user. See
Figure 68.
The factorial of '6' is
1*2*3*4*5*6 = 720.
Vectors and lists are container classes, part of the Standard Template Library
(STL). This is a general-purpose C++ library of algorithms and data structures
that we can use in our programs. While some aspects of the library are very
complex, it can often be applied in a very straightforward way that allows reuse of
sophisticated data structures and algorithms.
As with an array, v e c t o r and l i s t can hold objects of various types. However,
unlike arrays, vectors and lists can resize, shrink and grow as elements are added
or removed.
The standard library provides access via iterators, or subscripting. Iterators are
classes that are abstractions of pointers (more on pointers later). They provide
access to container classes using pointer-like syntax and have other useful
methods as well.
The use of vectors, lists and iterators is preferred to arrays and pointers. By using
containers common problems involving accessing past the bounds of an array are
avoided. Additionally, the C++ standard library includes generic algorithms (an
algorithm is a set of instructions on how to perform a task) that can be applied to
vectors lists and other container classes.
N o t e : Arrays have been used in C++ for many years and there will be code you
work with that was written before Vectors. Vectors are new in C++ and are
preferred to arrays and pointers. Common problems involving accessing past the
bounds of an array are avoided when using vectors.
Task 1
In eclipse, open the Compile the program, sorting any compilation errors.
project Array
Run the program adding five exam results. The
output should be similar to Figure 69.
Figure 69
Step 1
Examine the following statements
d o u b l e E x a m M a r k s [ 5 ] = { 0 } ; This statement
declares the array, setting it’s size to 5 elements and
explicitly initialising all elements to zero.
c o u t < < " E n t e r E x a m M a r k " < < i + 1 < < " " ; This
statement prompts the user to enter an Exam mark
into the array at element i + 1 .
Using the notation i + 1 indicates to the user to enter
E x a m M a r k 1 not exam mark 0 which would be less
intuitive.
Array elements are numbered from 0 to n-1. So an
array that holds 2 0 i n t e g e r s will be addressed from
element 0 t o 1 9 .
ExamMarks[0]…ExamMarks[19]
The first number will be entered into element [ 0 ] .
The last into element [ 1 9 ] .
cin>>ExamMarks[i];
This statement reads in the user input and stores the
values in the array elements of E x a m M a r k s [ i ] . i is
incremented within the f o r loop and starts at 0 .
Task 2
Modify the program to
calculate the highest and
lowest numbers in the
array.
Task 3
Create another project
call it N a m e s . The
program should read in
student names, these
will be held in an array.
The user should enter
three names. The names
should be output to
screen, see Figure 70.
Although not part of the
STL, the string class is
part of the ANSI C++
standard library and has
many useful member
functions. (See
Appendix 24.16, String
class). Figure 70
Task 4
OPTIONAL
Create another project
call it A r r a y N a m e A g e .
The program should
read in two patient
names with their age.
The user should be
prompted to add the age
after the name has been
added.
The output should be as Figure 71
shown in Figure 71.
Modify the program to
establish the average
age. Output the result.
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project LinearSearc
h Run the program; choose a number between 1 and
1 0 0 . The output should be similar to Figure 76.
Figure 72
Step 2
Examine the following statements
m y A r r a y [ i ] = ( 1 + r a n d ( ) % 1 0 0 ) ; This statement
uses the r a n d function, part of the < c s t d l i b > header
file. r a n d ( ) % 1 0 0 produces integers in the range 0 to
99.
The function l i n e a r S e a r c h takes three arguments.
The array name, the size of the array, the third
argument is the search value.
if ( array[j] = = value )
return j;
This selection statement compares each element to
the search value. If the search value is in the array the
element number is returned to m a i n ( ) otherwise -1 is
returned.
The i f selection statement i f ( e l e m e n t ! = - 1 ) in
m a i n ( ) is used select the output indicating a
successful or unsuccessful search.
Task 2 Step 1
Create another program Create a project, call it S e a r c h C o u n t V a l
to output a count of the
Create a new source file S e a r c h C o u n t V a l . c p p
individual numbers held
in an array. The Create a header file S e a r c h C o u n t V a l . h
numbers in the array
should be randomly
generated. The output Step 1
should be as shown in Write the program, creating an array of random
Figure 73. numbers. Create a small array of 1 5 elements and
add random numbers to the array using the r a n d
function. The random numbers should be between 0
and 1 4 .
You will need to # i n c l u d e < c s t d l i b > for rand()
Step 1
The user should be prompted to enter a number.
Search the array until the number is found or the end
of the array is reached.
Provide an output indicating whether the value is
present or not in the array.
Step 1
Create a second array that will store in each element a
count of the number of times each randomly
generated number appears in the first array i.e. if 10
appears twice in the array of randomly generated
numbers, element 10 in the second array should show
2.
Make sure your array size is 15 elements and the
randomly generated numbers in the first array are
between 0 and 14.
Output the contents of the second array to screen as
shown in Figure 73
The input and output should be in a loop so the user
can test the program repeatedly. Remember to add a
statement to terminate the program.
Figure 73
Task 1 Step 1
Create a new From the directory where you unpacked the
project, call it Inserti source materials, open the file called Insertio
onSortClass n S o r t . h and add it to your project.
Examine the code. The class file is used to sort an
array of integers passed from the main() program
The sort works by first looking at array elements
s o r t [ 0 ] and s o r t [ 1 ] . If the first two values are in
order the program continues otherwise they are
swapped.
In the second iteration the program looks at element
s o r t [ 2 ] and compares this to s o r t [ 1 ] . If the value in
s o r t [ 1 ] is greater than the value in s o r t [ 2 ] the values
are swapped. The while loop is then used to compare
the value in s o r t [ 1 ] to the value in s o r t [ 0 ] .
This iterative process continues until all array
elements have been sorted.
Task 2 Step 1
OPTIONAL Add # i n c l u d e " I n s e r t i o n S o r t . h "
Add a new source file to Create an instance of the class S o r t A r r a y m y A r r a y ;
the project call it Create an array of 200 randomly generated numbers,
InsertionSort.cpp numbers[i] = (1 + rand()%100);
Step 1
Call the class member function
myArray.sortArray(numbers,SIZE);
Output the sorted array
cout<<setw(4)<<numbers[i];
See Appendix 24.8 for more detail on formatting
output.
Figure 74 and Figure 75 show the array before and
after sorting.
Figure 74
Figure 75
Task 4
Create a second object,
call it y o u r A r r a y .
Create an array of 50
randomly generated
integers between 1 and
50.
Output this array before
being sorted and after
being sorted.
Output a count of the
number of times each
number appears in the
sorted array.
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project MultiDimArra
y Run the program adding 2 exam results for each of
the two students. The output should be similar to
There is one associated Figure 76.
file
MultiDimArrayMain.c
pp
Figure 76
Task 2 Step 1
Examine the code used Examine the following code segments
to write values to and
d o u b l e E x a m M a r k s [ 2 ] [ 2 ] = { 0 } ; This statement
read from a
creates a two-dimensional array having two rows and
multidimensional array.
two columns and initialises the elements to 0.
Every element in the array is identified by an element
name in the form a [ x ] [ y ] , where a is the name of the
array, and x and y are the subscripts that uniquely
identify each element in a . Notice that the names of
the elements in row 0 all have a first subscript of 0 ,
see Table 5. The names of the elements in column 1
all have a second subscript of 1 .
N o t e : multidimensional arrays can have two or more
dimensions (subscripts). Three-dimensional arrays
are uncommon.
Column 0 Column 1
Row 0 a[0] [0] a[0] [1]
Row 1 a[1] [0] a[1] [1]
Table 5
Step 1
Examine the following code segment used to read
values in to the array
for(int row = 0; row < 2; row++)
cout<<endl;
Step 1
Examine the following code segment used to calculate
the total of each student’s marks.
if(row ==0)
r1total += ExamMarks[row][col];
else
r2total += ExamMarks[row][col];
Task 6
Modify the program to
read in 5 exam marks for
four students.
Establish the highest,
lowest and average mark
for each student. Output
the results.
Establish the highest and
lowest marks overall.
Output the results.
Task 7 Step 1
Create a new A multi-dimensional array has been created and
project, call it Matrix initialised with 80 integers. From the directory where
Manipulation. you unpacked the source materials, open the file
This program will called m a t r i x . t x t . Add this to your program.
manipulate a matrix of The output from the program should be the same as
integers. Each row of shown in Figure 77.
data is totalled and
appended to the row.
Each column of data is
totalled and appended to
the column.
The sum of the contents
of the entire array are
calculated and added
between the row and
column totals
Figure 77
You can sort the order of elements in a vector (v e c ) for example, by using the
s o r t algorithm.
sort(vec.begin(), vec.end());
There are two important points to notice about the call to r e v e r s e . First, it is a
g l o b a l function (as are f i n d and s o r t ) not a member function. Second, it takes
two arguments rather than one and operates on a range of elements, rather than
on the container (vector container in this case).
With the above examples the range is the entire container from b e g i n ( ) to e n d ( )
(vec.begin() to vec.end()). r e v e r s e , like the other STL algorithms, is
decoupled from the STL container classes. The r e v e r s e algorithm can be used to
reverse elements in v e c t o r s , in l i s t s (another container), and even elements in
C arrays.
In the above example the first argument to reverse is a pointer (pointers are
covered in Section 11 but for now we can say the first argument points to the
address in memory that is the start of the vector) to the beginning of the range,
and the second argument points one element past the end of the range. This
range is denoted (myArray, myArray + 4);
Arguments to reverse are i t e r a t o r s , which are a generalization of pointers which
is why it is possible to reverse the elements of a C array using the array address
and pointer notation.
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project VectorDemo
Run the program adding five exam results. The
There is one associated output should be similar to Figure 78.
file V e c t o r D e m o . c p p .
Figure 78
Step 2
Examine the following statements
# i n c l u d e < v e c t o r > ; This statement includes the
header file < v e c t o r > enabling the program to use the
class template v e c t o r . (templates allow the use of
generic functions that admit any data type as
parameters and return a value, more on this later.).
v e c t o r < d o u b l e > E x a m M a r k s ( 5 ) ; This
statement declares the vector to hold doubles and sets
the initial size to 5 elements.
N o t e : Although vectors can grow to any size it is
good practice and more efficient to specify the size
when this is known. When no size is given and the
contiguous memory spaces have been exhausted the
elements must be copied to a larger memory space to
increase the size of the vector.
c i n > > E x a m M a r k s [ i ] ; This statement reads in the
user input and stores the values in the vector slot i of
E x a m M a r k s [ i ] . i is incremented within the f o r loop
in a similar way as in the previous array exercises
using the subscript operator [ ] .
Task 2 Step 1
From the directory Copy the code from V e c t o r . t x t and add it to
where you unpacked the V e c t o r . c p p immediately above the return
source materials, open statement ;
the file called
Run the program entering 5 numbers. Follow the
V e c t o r . t x t . Copy the
prompts and add an additional number to the vector.
code and add it to
The output should be as shown in Figure 79.
Vector.cpp
Examine the following statement
ExamMarks.push_back(test);
p u s h _ b a c k ( ) is a member function of the vector
class that adds an additional vector element at the end
and passes the variable test as a parameter to the
vector.
The size of the vector is now six elements.
Figure 79
Task 4
Modify the program to
delete the last element
and output the vector
slots showing all values.
p o p _ b a c k ( ) is the
member function that
can be used to delete the
last element in a vector.
Task 5
Create a new
project, call it Vector
Sort.
In the program create a
vector of 100 randomly
generated numbers.
Output the contents of
the vector before and
after sorting.
See Appendix 24.13 for
more detail on vectors.
There are many types of penguin and the data for each type will be kept
in instances of a class and the objects stored in a vector.
Task 1 Step 1
Create a new In main() create a vector of penguin objects:
project, call it
vector<Penguins> myPenguin(2);
VectorofPenguins.
Create a header file Print out the default contents of the vector
P e n g u i n s . h and add Loop through the vector adding two objects
member functions to for(int b = 0; b < 2; b++)
allow the user to add and
change the penguin type {
and colour. //Read in the penguin type and colour
Add the necessary
constructors and
/*create first object*/
destructors including a
default constructor that myPenguin[b] = Penguins(name, colour);
will name a type as }
"King" with a colour
"Black, Grey & Orange"
when called.
You will need data
members to store these
values.
In m a i n ( ) add a vector
to store each object
instantiated.
Add two objects using Figure 80
code similar to that
shown in step 1 then add
another penguin object Object member functions can be accessed using the
using vector member following notation.
functions.
Output the contents of cout<<myPenguin[a].getName()
the vector to screen, it
should be similar to
Figure 80.
Figure 82
Figure 83
This statement uses the member function i n s e r t ( )
and iterator i t to insert 200 at the beginning of the
vector (i t ).
Note that an iterator is returned by the function
i n s e r t ( ) that points to the newly inserted element.
Step 1
Examine the code shown in Figure 84
Figure 84
Step 1
Examine the code shown in Figure 85
Figure 85
Figure 86
Task 4
Add the code shown in
Figure 87 to the program
and using the i n s e r t ( )
member function add
the array to the n u m s Figure 87
vector. Output the
contents of the n u m s
vector to screen.
lists are declared indicating the type and number of elements in the following
way:
list<type> listName;
list<type> listName(initialSize);
list<type> listName(initialSize, elementValues);
Examples are:
list<double> inNumbers; a list called i n N u m b e r s with no initial size
to hold d o u b l e s .
list<char> Name(20); a vector called N a m e with an initial size 20 to
hold characters.
list<int> ExamMarks(4,6); a vector called E x a m M a r k s holding integers
with initial size of 4 elements each with the
value 6
N o t e : In the following exercises you will use some of the l i s t class member
functions found in the Standard Template Library (STL). Some of these are
b e g i n ( ) , e n d ( ) , s o r t ( ) , and s w a p ( ) .
The STL also includes a large collection of a l g o r i t h m s that manipulate the data
stored in lists. See section 24.14 for more detail.
Task 1 Step 1
In eclipse, open the Examine the statement shown in Figure 88
p r o j e c t M e r g e , and
examine the program
works.
Figure 88
This statement creates two lists to hold doubles,
l i s t O n e and l i s t T w o .
Figure 89
This statement creates a third list and initialises it
with two elements each holding 9.69.
Step 1
Examine the statement shown in Figure 90
Figure 90
This statement creates an iterator for looping through
lists. The iterator type for a l i s t is bidirectional. Note
that the iterator type for a v e c t o r is random access.
The twelve statements following the iterator
declaration use the class member function
p u s h _ b a c k ( ) to add new elements at the end of each
list.
The p u s h _ b a c k member function is common to
vectors and lists.
Step 1
Examine the statement shown in Figure 91
Figure 91
This statement uses member function s o r t ( ) to sort
listOne.
Note that lists do not use the sort algorithm that we
used with the vector class as the sort algorithm only
works with random access iterators, the type used
with vectors.
Lists use bidirectional iterators so there is a member
function l i s t O n e . s o r t ( ) provided.
Step 2
Examine the following statements
Figure 92
list iterator i t is used to loop through the elements of
the list.
l i s t O n e . b e g i n ( ) returns an iterator to the beginning
of the list.
l i s t O n e . e n d ( ) returns and iterator to the end of the
list.
i t and the dereference operator * are used to output
the values in the vector, * i t .
Step 3
Examine the following statement
Figure 93
This statement merges the second list into the first
list.
All the elements of the second list are inserted into the
first list at their respective ordered positions.
N O T E : This empties the second and increases the
size of first list.
Task 4 Step 1
In this task you are The l i s t T h r e e o b n e c t i s r e s i z e d t o to the same
asked to examine size as l i s t T w o using the list member function
m a i n M e r g e . c p p which r e s i z e ( ) so that the list can hold all the elements
copies the contents of copied.
l i s t T w o to l i s t T h r e e .
Arguments to r e s i z e are the size of l i s t T w o . The
Note that c o p y is an l i s t T w o member function s i z e ( ) is used to get this
algorithm not a member value.
function of the list class.
Copy the contents of l i s t T w o to l i s t T h r e e
The syntax for the copy algorithm is:
iterator copy( iterator start, iterator end,
iterator destination );
The return value ‘i t e r a t o r ’ is an iterator to the
destination of the last element copied.
10 More on Functions
Functions are used to encapsulate a set of operations and return information to
the main program or calling routine. Encapsulation is data, information or detail
hiding.
Once a function is written, the detail of how it works is not important to the end
user. The user needs to understand what data to input and what output will be
produced.
In the following exercise you will pass multiple arguments to a function. The
arguments must be specified in the prototype, each argument is separated by a
comma. The exercise will also detail how to add default arguments in the
prototype.
Task 1 Step 1
Create a new The function prototype you create should be similar to
project, call it Salary
. Name the source file void CalcSalary(double grossSal, double IT,
Salary.cpp. double NI = 5.0);
The program should N o t e : In this prototype we are passing multiple
read in a g r o s s s a l a r y arguments. Each argument is separated by a comma.
and rate of Income Tax
A default argument double NI = 5.0 has been also
(I T ).
used in the prototype above. Default arguments must
The s a l a r y , I T and be declared at the end of the list of arguments.
National Insurance rate
Because we are using a default argument for the
(N I ) will be passed to a
national insurance rate it is only necessary to read in a
function to calculate and
gross salary and the rate of income tax.
display the take home
pay. Gross salary and income tax are passed to the function
from main() in the statement
Take home pay is
C a l c S a l a r y ( g r o s s S a l , I T ) ; along with the default
calculated as follows:
NI argument specified in the prototype.
TakeHomePay =
(grosspay*(1-NI))*(1- All three arguments are used in the function to
Income Tax) calculate the take home pay.
Remember, default arguments must be declared at the
end of the list.
Step 2
Create a function call it c a l c S a l a r y
The function will receive three arguments, the
definition is shown below
void CalcSalary(double grossPay, double IT,
double NI)
The formula for calculating the take home pay is:
TakeHomePay = (grossPay*(1-NI))*(1-IT);
Task 3
ONLY ATTEMT THIS IF
YOU HAVE
COMPLETED
CHAPTER 7
Create an o b j e c t for
each member of staff.
Create separate member
functions to change the
rate of N I and I n c o m e
Tax.
Task 1 Step 1
In eclipse, open the Run the program. The output should be the same as
project Temperature shown in Figure 94.
s R e t V a l u e s and
modify the program.
Figure 94
Step 2
Examine the function prototype
int FtoCent(int temp, int ch);
This function prototype has a return type of int.
When the function is called and calculations
completed an integer is returned to the calling
statement.
Step 3
Exam the calling statement
retValue = FtoCent(I_far, choice);
The function call F t o C e n t ( ) passes arguments I _ f a r
and choice. The value returned is assigned to
retValue
Step 4
Examine the function definition. The function
definition matches the prototype indicating two
integers are being passed to the function and an
integer is being returned.
int FtoCent(int ITemp, int ind) {}
Step 5
Examine the function body. The two statements
below convert the temperature input. The conversion
type required is identified using the user input i n d
and i f selection.
The statement I _ f a r = ( I T e m p - 3 2 ) * 5 / 9 ; is
used to calculate the temp in centigrade
The statement I _ f a r = s t a t i c _ c a s t < i n t > ( I T e m p *
1 . 8 + 3 2 ) ; is used to calculate the temp in farenheit.
The last statement in the function is return I _ f a r ;
This statement returns the temperature I _ f a r to the
calling statement in m a i n ( ) .
N o t e : The data being returned must be the same data
type as defined in the function prototype. In this
example an integer.
Task 6 Step 1
(REQUIRES Modify the program so take home pay is returned
COMPLETION OF 27) from the function and output to screen from within
main().
Open the S a l a r y project
you created in Exercise If you completed Exercise 27Task 2, you will need to
27 Functions with add a member function of the class to achieve this.
multiple arguments and
default values.
Task 7
OPTIONAL
Create a new project, call
it
ReturnExperResults
The program will read in
5 experimental results.
Read the results in to the
main program and pass
them to a function.
The function should
calculate the maximum
value. This should be
returned and displayed
within main.
Task 1
Open the project you
created in the last task,
ReturnExperResults,
Exercise 28 Task 7.
Create a class call it
E x p e r i m e n t r e s u l t s in
a new file called
ReturnExpResults.h.
The values read in to
m a i n ( ) should be passed
to a function called
readNumbers( ) in
main().
From within the function
readNumbers( )
create an object of the
class
Experimentresults.
From within the function
pass the values read in to
a constructor of the
class.
The average value
should be calculated
within class member
functions. Use member
functions to return
values to the calling
function.
The average mark should
be returned to m a i n ( )
from the function
r e a d N u m b e r s ( ) , then
output to screen.
Task 1 Step 1
Create a new project, call Create a new project, call it call it
it A r r a y R e t u r n V a l u e . ArrayReturnValue
Pass an array to a Create a function prototype d o u b l e
function and read in five calcAverage(double ExamMarks[], int num);
numbers. E x a m M a r k s [ ] is the array being passed. As with
Calculate the average passing variables, it is not strictly necessary to pass
value in the array, return the name of the argument, just its type. This could
this to m a i n ( ) and have been written as c a l c A v e r a g e ( d o u b l e [ ] , i n t
output to screen. n u m ) ; However, it is useful for future reference as it
helps explain how the function works.
At the end of the
program output the It is also necessary to pass the size of the array. n u m
values in the array from is the number of elements in the array, it’s size.
within m a i n ( ) . Step 2
Within m a i n ( ) declare the array and initialise the
elements to zero with the following statement d o u b l e
ExamMarks[5] = {0};
This declaration explicitly initialises the first element
to zero and implicitly initialises the remaining four to
zero
Step 3
Create a function d o u b l e c a l c A v e r a g e ( d o u b l e
ExamMarks[], int num) { }
Read in the values and calculate the average
Add the code to establish the average of values in the
array
Return the average value to main() and output
Step 4
Call the function from within m a i n ( ) with the
following statement
average = calcAverage(ExamMarks, 5);
Step 5
At the end of m a i n ( ) add the statements
for(int i = 0; i < 5; i++)
cout<<"Exam Mark Number "<<i + 1<<" is
"<<ExamMarks[i]<<endl <<endl;
Step 6
Explain how it is possible at the end of the program to
output from within m a i n ( ) all the values in the array
entered within the function
In previous exercises when parameters (variables)
were passed to functions the function received a
v a l u e . When a v a l u e is used in a function a copy is
stored in a part of memory that only exists from the
time the function is called to when it ends. After this,
the memory and any v a l u e in it are lost.
However, the array in this exercise was initialised in
m a i n ( ) with zeros and then passed to the function.
Data was then added to the array and calculations
done. At the end of mai n ( ) the values in the array
elements are output. The array contains values input
from within the function.
When the function is called
c a l c A v e r a g e ( E x a m M a r k s , 5 ) the name of the
array, E x a m M a r k s is passed.
Task 8
Modify your program so
that the calculations are
done in a class file. Pass
the array to the class
using a constructor.
Task 9
Go back to Exercise 21
and modify the header
file to sort the array
passed using the global
vector function s o r t ( ) .
You should be able to
replace the whole
member function
functionality with one
statement.
N o t e that you will have
to change the class
member function name
from s o r t to another
name. Defining a
member function name
the same as a vector
function name will cause
a compilation error.
Choose your own
function name or use
sortArray().
Task 10
Continuing from the
previous task, when you
have sorted the array
add another member
function to reverse the
array.
Call the new member
function and check the
array has been reversed.
Table 7
Task 1
Create a new project, call
it call it
ArrayMultRetVal.
The program will read in
bank account deposits
for two customers and
output the balance of
accounts.
The customer will be
prompted to enter
deposits and these will
be stored in a two-
dimensional array. Figure 95
Step 2
Create a second function v o i d p a s s B a l a n c e s
( d o u b l e B a l a n c e [ ] [ c o l S i z e ] , i n t r S ) after m a i n ( )
Calculations to establish the interest and balance for
each customer should be done in the inner loop
(c o l u m n ) of the array search. The following
statements will establish the deposit, interest and
total for each deposit
deposited += Balance[r][c];
interest +=Balance[r][c]*0.05;
total +=(Balance[r][c]*(1 + 0.05));
The calculations to total all deposits need to be done
in the outer loop (r o w s ) of the array search
OAdeposited += deposited;
deposited = 0; /*reset the amount deposited
for next customer*/
OAinterest +=interest;
interest = 0; /*reset the interest for next
customer*/
OAtotal +=total;
total = 0;
Step 3
Call the functions from within main() with the
following statements.
getDeposits(Balance, rowSize);
passBalances(Balance, rowSize);
Task 5
Modify the program you
have just created using a
class defined in a
separate header file.
Pass the array to the
class object.
All calculations should
be done within the class
file and output via
member functions.
Task 1 Step 1
In eclipse, open the Run the program. The output should be the same as
project Overloading shown in Figure 96.
F u n c t i o n s . Examine
the program structure.
There is one source file
OverLoadingFunction
s.cpp.
Figure 96
Step 2
Examine the function prototypes
void FtoCent(int temp);
void FtoCent(double temp);
Step 3
Examine the statement
i n V a l u e = t o u p p e r ( i n V a l u e ) ; t o u p p e r is a
member function in header file < c c t y p e > that
changes the input char to upper case. Using t o u p p e r
means it is unnecessary to test for upper and lower
case values input.
Step 4
Examine the function definitions.
The two function definitions have the same name but
different types of argument. In this example the
compiler is selecting the correct function on the single
argument type being passed.
Step 5
Examine the function v o i d F t o C e n t ( d o u b l e
I T e m p ) used to convert a double value read into
centigrade.
The statement c o u t < < f i x e d < < s e t p r e c i s i o n ( 2 ) ;
This statement sets the stream manipulators, f i x e d
and setprecision. Another stream manipulator used
in this function is s e t w . The header file < i o m a n i p >
must be included to use these stream manipulators.
When several numbers are displayed each is printed
with the minimum number of digits needed to show
the value. This can produce some unexpected output
results.
The width of an output field can be set using a stream
manipulator setw. To set the next number to be
printed to a width of 5 digits use c o u t < < s e t w ( 5 ) .
This command does not produce any output but
manipulates the stream to change the output format
of the next value. Note: setw must be specified for
every item output.
Task 1 Step 1
In eclipse, open the Run the program, adding data as requested. The
project FunctionTem output should be the same as shown in Figure 97
p l a t e . Examine the
program structure.
There are two associated
files:
FunctionTemplate-
Maximum.h
FunctionTemplate-
Maximum.cpp.
Figure 97
Step 2
Examine the header file F u n c t i o n T e m p l a t e -
Maximum.h
F u n c t i o n T e m p l a t e - M a x i m u m . c p p is used to
prompt the user to enter three integers, three doubles
and then three characters. This demonstrates how
one template function can be used instead of function
overloading when the program logic and operations
are the same for all data types.
Task 3 Step 1
Create a new Create two files in the project. A class definition and
project, call it Functi the client code.
onTemplateArrays.
In the header file create the class S h o w A r r a y
In the class create a function template as shown in
Figure 98 (or copy from FunctionTemplate-
Arrays.txt)
Figure 98
Step 2
In m a i n ( ) create three arrays. One with 45 randomly
generated doubles, one with 45 integers and one with
10 strings.
Create an object of class S h o w A r r a y with the
statement S h o w A r r a y m y S h o w A r r a y ;
Call the template function passing the three arrays in
turn.
This shows that when the program logic is the same
for all data types function templates can be used for
function overloading. See Figure 99.
Figure 99
11 Pointers
Declarations:
int C; This is a standard variable declaration C , that contains a value as yet
unknown of type int.
int *C; This is a pointer C , that will point to an address in memory containing
a value of type int.
Each variable declared as a pointer must be preceded by an asterisk (* ).
int *age, height; a g e is a pointer, h e i g h t is a value.
double *far, *cent; are both pointers to double values.
Pointers must be initialised when they are declared, or in an assignment. It is
common to initialise pointers to a memory address but they can also be initialised
to zero. A pointer pointing to 0 is called a n u l l p o i n t e r .
Note:
When the * is used in a variable declaration it indicates the variable being
declared is a p o i n t e r and not a v a l u e .
But do beware, when the * appears before a pointer variable elsewhere in the
program it acts as an operator, called the d e r e f e r e n c e o p e r a t o r . It causes
tohe program to look up the value that the pointer references – i.e the data stored
at the address of that pointer.
To complicate matters further using the pointer name without the dereference
operator in the program references the address in memory.
Once declared, a pointer variable can be assigned the address of another variable
using the & “a d d r e s s o f o p e r a t o r ”.
Note: we have seen the & before when declaring references to values. In that
case, we saw it when the value was declared. Here we see its use as an
operator.
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project Pointers.
There is one associated Run the program. The output should be the same as
file, Figure 100.
PointersMain.cpp.
Figure 100
Step 2
Examine the following statements. Only the
important parts of the program are explained, the rest
has been covered in previous exercises.
int *x_ptr = &x; This is x _ p t r pointer
declaration and initialisation.
y _ p t r = x _ p t r ; Assigning x _ p t r address t o y _ p t r .
Both pointers are pointing to variable X ( 1 6 ) .
The pointer has been declared and initialised with the statement int *x_ptr =
intArray; Note: there is no need to use the address of operator & when
initialising arrays as the array name is the address of the beginning of the array.
When working with arrays each element of the array will be the type and size at
declaration. When an array is declared to hold integers, each element will be 4
bytes in size. An array of doubles will have element sizes of 8 bytes.
It is not important to know how many bytes make up each element. Moving the
pointer through the array with the assignment operator x _ p t r + = 2 will move
two elements further through the memory allocated for the array, or 16 bytes for
an array of doubles.
Task 1 Step 1
In eclipse, open the Compile the program, sorting any compilation errors.
project PointerArith
m e t i c . There is one Run the program. The output should be the same as
associated file, Figure 101.
PointerArithmeticMai
n.cpp.
Figure 101
Step 2
Examine the following statements in the program.
Only the important parts of the program are
explained, the rest has been covered in previous
exercises.
i n t * x _ p t r = i n t A r r a y ; this is the pointer
declaration and initialisation. Note: The name of the
array is the address of the first element.
for (i = 1; i<5;i++)
{
x_ptr++;
cout <<"The VALUE stored in ELEMENT
"<<i+1<<" is " <<*x_ptr <<endl;
}
x _ p t r - - ; (there is no preseeding d e r e f e r e n c e
o p e r a t o r therefore the pointer is pointing to a
memory a d d r e s s ) moves the pointer one a d d r e s s
back along the array. As this statement is in a f o r
loop that repeats four times the pointer has been
moved back to the beginning of the array.
In m a i n ( ) create an
array of 20 random
numbers of type double.
Task 3 Step 1
Create a new From the directory where you unpacked the
project, call it Array_ source materials, open the file called Array_
Algorithm. Algorithm.txt
Use STL global functions Replace the default source file in the project with
to manipulate an array. Array_Algorithm.txt
Add the necessary code so the output is the same as
that shown in Figure 102.
Figure 102
reverse(A, A + 6);
Task 4
OPTIONAL
Now you have seen how
to find values in an array
go back to Exercise 21
and add functionality in
a new member function
to allow the user to
search for numbers
repeatedly until they end Figure 103
the program. See Figure
103.
Task 1 Step 1
In eclipse, open the I n e c l i p s e , o p e n t h e p r o j e c t H e a d e r . If you
p r o j e c t H e a d e r . There do not have this project, go back to Exercise 13 and
should be one associated complete the task.
source file:
OxStudents.h.
Add a new Source file to the project, File | New |
Source File
Modify the header file to
create class definitions. Save and name the file O x S t u d e n t s . c p p .
Figure 104
Step 1
Add the directive # i n c l u d e " O x S t u d e n t s . h " at
the top of O x S t u d e n t s . c p p
Compile the program
You should get a compilation error indicating a
redefinition of class O x S t u d e n t s . The class has
already been defined in the . h file and a class
cannot be defined twice.
Step 1
Remove the class definition by removing the line
c l a s s O x S t u d e n t s and the closing curly brace
and semi-colon at the end of the file
Remove p u b l i c :
Change the function headers to match Figure 105 .
Figure 105
Notice that d i s p l a y N a m e is now preceded by the
class name, O x S t u d e n t s and :: the b i n a r y s c o p e
r e s o l u t i o n o p e r a t o r . The member function is
now related to the separate O x S t u d e n t s class
definition that contains the class data members
and member function definitions.
Compile and run the program
Task 6
OPTIONAL
Go back to the other files
you have created and add
interfaces to these projects.
13 Session 2
13.1. files used
Files & Folders you will need. These are available from:
http://www-
pnp.physics.ox.ac.uk/~brisbane/cplusplus_2013/EclipseStudentFiles_part2.tgz
Birds
Composition
FriendClass
Friends Function
FuncRefValinline
HumPlacMammal(StudDefinitions)
Inheritance Dynamic
InheritanceStaff
Java.txt
Mult Base Class - StudentTeacher
Multiple Inheritance
Operator Overloading +
Overload STREAM INSERTION
OverRideBaseClassmeths
Polygon
PurVirtualFunctions
RefSalary
RefSalary2
strcatStrncat
Student ATM Abstract Balance Inquiry
Task 1 Step 1
In eclipse, open the Open the P a s s B y R e f F u n c project.
project FuncRefValInli
ne. Step 1
Examine the structure of Run the program. The output should be as shown
the project to identify in Figure 106.
different inline function
calls, and the use of
pointers and reference
arguments with function
calls.
Figure 106
Step 2
Examine the function prototypes shown in Figure
107.
The first prototype shows passing an integer value
to a function. A copy of the variable is passed to
the function.
The second statement shows passing a reference to
a function. The address of the variable is passed to
the function.
The third statement shows passing a reference to a
function using a pointer. The address of the
variable is passed to the function.
The fourth function prototype shows how a default
argument can be passed to a function. If the user
supplies an argument in the function call this will
override the default argument.
Figure 107
Step 3
Examine the variable declarations shown in Figure
108.
The first three statements are standard variable
declarations.
int *wPtr; declares a pointer of type integer.
wPtr = &w; assigns the address of variable w to
the pointer.
int &zRef = z; z R e f is a reference to z .
References must be initialised when declared.
Figure 108
Step 4
Examine the statement shown in Figure 109. : : is
the u n a r y s c o p e r e s o l u t i o n o p e r a t o r and is
used to access the global variable x (20) with the
same name as the local variable x (20). The local
variable can be accessed using the standard
notation.
Figure 109
Step 5
Examine the rest of the program and then add
z R e f = & w ; as shown in Figure 110.
Compile the program.
Explain what is happening and why the program
will not compile.
Figure 110
Figure 111
Figure 112
Figure 113
Figure 111 shows a function prototype with two parameters. A s t a f f object and
double.
Figure 112 shows the function call with an instance of S t a f f called J o h n being
passed with a d o u b l e 1 0 .
Figure 113 shows the function body. It receives the two parameters. The staff
object e m p is set to the same value as John and amount is set to 10. e m p is then
modified but the modification has no effect on John as e m p is a separate object.
When the function exits e m p is forgotten and John doesn’t get a raise, most
unsatisfactory.
I n t h e f u n c t i o n r a i s e S a l a r y ( ) , e m p is a value parameter because it is a
variable initialised with a value supplied by the caller. We want e m p to refer to
the instance object J o h n . We also need the salary of J o h n to be updated with
changes calculated within the function. To achieve this we make e m p a
r e f e r e n c e parameter.
When parameters are declared in this way they are bound to the variable in a
function call and allow the function to modify the variable.
Task 1 Step 1
In eclipse, open the Open the S t a f f project.
project RefSalary.
Examine the structure of
project and establish how Step 1
the program works. Run the program. The output should be as shown
in Figure 114.
Modify the program to use
reference parameters so
e m p is a reference to an
existing instance object
John.
Figure 114
Obviously there is a problem somewhere; John
Black has not received the payment with the
increase in salary.
Step 2
Modify the program, to use reference parameters.
This means pass a reference to the instance object
(the address) to the function. Compile and run the
program again
The output should be as shown in Figure 115.
Figure 115
Step 3
The answer is in section 14.2.
After a reference has been declared it cannot be changed. Any attempt to refer
the reference to another object (as we can do with pointers) will cause a
compilation error.
Since we cannot change a reference after it has been defined, a reference must be
assigned to an object when it is declared.
double &const x = a;
declares a constant reference and will cause a compilation error. R e f e r e n c e s
are constant by default.
Task 1 Step 1
In eclipse, open the Look at all the files in the project and modify the
project RefSalary2 program so that c o n s t references, pointers, objects
Examine the structure of and member functions are addressed correctly.
the project and establish
how the program works.
This is very similar to the Step 1
program you used in When the program is compiled the output should
Exercise 38. be as shown in Figure 116 .
The program is using
constant pointers, constant
references and should be
using constant member
functions.
Modify the program so the
const pointers and objects
are being used correctly.
Also check the member
functions have been
correctly written and are
not being used to modify Figure 116
any const data.
15 More on Classes
15.1. Inheritance
Inheritance is an important feature of classes; in fact, it is integral to the idea of
object-oriented programming.
Inheritance allows us to create a hierarchy of classes. As the hierarchy grows
classes become more specific.
Specific classes inherit the more general aspects of the classes above them in the
hierarchy, see Figure 117.
In this way it is possible to structure a program starting with abstract ideas that
are then implemented by specific classes.
Figure 117
Figure 117 shows a hierarchy of potential classes. Mammals might be one of our
classes. The classes Placental Mammals, Monotremes and Marsupials all inherit
traits that are general to all Mammals. Each of these classes will also have
attributes specific to the Placental Mammals, Monotremes or Marsupial class.
Note also that Mammal is a class derived from Vertebrates and so would inherit
attributes of that class.
As an aside, let’s see what the characteristics of Mammals, Placental Mammals,
Monotremes and Marsupials are. This will help determine the data members and
class member functions we need to add to the three classes.
Mammals.
Mammals are vertebrate animals that are endothermic (warm blooded), have hair
on their bodies, and produce milk to feed their babies.
Placental Mammals
The young of placental mammals develop inside the mother’s body while attached
to a placenta. Some examples of placental mammals are cats, bears, monkeys,
and humans.
Monotremes
Monotremes are the most primitive mammal and there are only three species: the
duck-billed platypus and two species of echidna (spiny ant eaters). These
mammals have hair and produce milk, but they also lay eggs.
Marsupials
Marsupials have tiny undeveloped young that grow inside the mother’s body
instead of in an egg. When they are born, they climb up the mother’s fur to a
pouch on her belly, settle and feed inside. Some well-known marsupials are
koalas and kangaroos
Figure 118
The syntax to denote one class as inheriting from another is simple and shown in
Figure 118. This shows a simple change in class declaration from the keyword
c l a s s used previously.
c l a s s C a t : p u b l i c b a s e _ c l a s s _ n a m e is the essential syntax for inheritance.
The syntax indicates that the class (C a t ) will contain all public and protected (see
section 15.3) data members of the base class (P l a c e n t a l M a m m a l s ). This does
not mean derived classes have access to all data members of a base class and the
specific instances of any derived class data.
The members, the variables and functions possessed by the derived class, are
specific to the type of class, not to each individual object of that type. Two
different Cat objects having the same members would most likely have different
information stored in their data members.
This is the most open level of data hiding. Anything that is public is available
to all derived classes of a base class. The public variables and data for each
object of both the base and derived class are accessible by code outside the
class. Functions marked public are generally those the class uses to give
information to and take information from the outside world; they are typically
the interface with the class.
The rest of the class should normally be hidden from the user and be private
or protected. The hidden nature and the highly focused detail of classes is
called e n c a p s u l a t i o n .
p r i v a t e : A data member or member function declared in a p r i v a t e
section of a class can only be accessed by member functions and f r i e n d s (see
section 15.7) of that class.
Private is the highest level of data hiding. Functions and data members
marked private are not accessible by code outside the specific object in which
that data appears. Note also that private variables and functions are not
inherited, but we can access them using public member (accessor) functions.
p r o t e c t e d : A data member or member function declared in a p r o t e c t e d
section of a class can only be accessed by member functions and f r i e n d s of
that class, and by member functions and friends of d e r i v e d classes. See
section 15.7 for more information on f r i e n d s .
One of the problems with using p r o t e c t e d data is that derived classes can
modify the base class data members directly (B a s e C l a s s : : D a t a M e m b e r ).
This means a derived class member functions does not have to use the get and
set member functions of the base class to modify protected data. A derived
class can then easily assign invalid values directly to protected data members.
Derived classes should depend solely on base-class services (base class public
member functions) and not on base class implementation. To achieve this we
should make data members private and provide public member functions to
manipulate this data.
Figure 120
Also included are two source code implementation
files m a n a g e r . c p p and s t a f f . c p p that contain
the detail of how the member functions work.
Step 3
Open m a n a g e r . h . Examine the class definition
class Manager : public Staff.
The : colon character denotes inheritance. The
keyword p u b l i c is required. However, if we omit
p u b l i c the class definition will still compile.
M a n a g e r will still inherit from S t a f f but will
inherit privately. This means that only the member
functions of M a n a g e r get to call the member
functions of S t a f f .
Whenever you invoke a S t a f f method on a
M a n a g e r object elsewhere the compiler will give
an error. Objects that you create should be usable
to other classes and making them private is not
considered to be good practice.
The interface m a n a g e r . h has p u b l i c member
functions and p r o t e c t e d data members that can
be accessed via members of it’s own class or
member functions of a derived class.
Note the use of the constructor to initialise the data
members of the class, p o s i t i o n and n u m S t a f f .
The separate source code file m a n a g e r . c p p
contains the detail of the member function
implementation.
Note the use of the pre-processor directive
# i n c l u d e " s t a f f . h " at the top of the file. This is
needed as the class m a n a g e r inherits from s t a f f .
Without it the m a n a g e r class does not know about
the s t a f f class members
Step 4
Open the file m a n a g e r . c p p . The separate source
code file m a n a g e r . c p p contains the detail of the
member function implementation and how the
functions work.
Note the use of c o n s t after the member functions.
Constant member functions that never change a
class member value should be declared as c o n s t .
See Appendix 24.18 for more detail.
Step 5
Open the file s t a f f . h . The interface s t a f f . h has
p u b l i c member functions and p r i v a t e data
members. Private data members can be accessed
via member functions of it’s own class or member
functions of the derived class m a n a g e r using base
class member functions.
Note the s e t member functions that are used by
the derived class to set the data members in the
base class.
There are also five c o n s t member functions to
return data from the base class object.
Step 6
Open the file s t a f f . c p p . The separate source code
file s t a f f . c p p contains the detail of the member
function implementation for the base class and
details how the functions work
Note the use of c o n s t after the member functions.
Again, constant member functions that never
change a class member value should be declared as
const.
Step 7
Open the file m a n a g e r M a i n . c p p . This is the
main file in which we create an instance of the
derived class manager called m a n 1 .
The user is prompted to enter the details for a
manager in the firm.
The number of staff the manager is responsible for
and their title are added to the instance data
members via the constructor.
All the other data is passed to the base class data
members via separate calls to the member
functions in the base class, ex.
Man1.setName(name);
The output is produced by calls to the instance
methods of the class, ex. M a n 1 . g e t N a m e ( ) ,
Man1.getnumStaff().
Note that these member functions are functions in
the base class s t a f f , not the derived class.
Figure 121
Step 2
Change the class header file m a n a g e r . h to match
the constructor implementation. Seven arguments
are being passed to the derived class.
Step 3
Modify the base class constructors S t a f f ( ) ; to
accept the five parameters being passed from the
base class initialiser list.
Step 4
Modify the statement M a n a g e r M a n 1 ( m a n T i t l e ,
n u m S t a f f ) ; in m a n a g e r M a i n ( ) used to create
and initialise the instance of M a n a g e r class.
When creating the instance of M a n 1 you will have
to pass all seven arguments.
Step 5
Remove the five statements from m a n a g e r M a i n ( )
that use base class member functions to initialise
the instance data members.
Compile and run the program. The output should
be the same as shown in Figure 119.
Figure 122
Task 1 Step 1
Add a preprocessor I n e c l i p s e , o p e n t h e p r o j e c t S t a f f file in the
directive to the s t a f f . h file I n h e r i t a n c e S t a f f folder.
in the project used in
Add a preprocessor wrapper to the s t a f f . h file.
Exercise 41.
Note: As there is only one derived class which uses
the staff class members it is not strictly necessary
to add a preprocessor wrapper to this class
definition. However, if we were to add another
derived class then there is the potential for the
header file to be included twice at compile time.
Task 1 Step 1
We need to add another Add two new files. You need to add a class
category of staff. Continue interface and a separate source code file (. c p p )
to use the program you that details the function implementation.
worked on in Exercise 42.
The administrator details you will need are the
The new category is building and office they work in.
Administrative staff.
Remember to use a member initialisation list.
A d m i n staff share all the
base class data members
attributes and can therefore
be treated as a derived class
of class s t a f f .
Modify the S t a f f project so
the program user can add a
new member of staff.
The user will be prompted
to add common staff details
and then to make a
selection as to the choice of
staff to add.
Figure 123 shows the sort of
interface needed.
Figure 123
Task 1 Step 1
In eclipse, open the Open O v e r R i d e B a s e C M project, compile and
project OverRideBaseC run the program. The output should be as shown
lassMeths. in Figure 124.
In eclipse, open the
project OverRideBaseC
l a s s M e t h s and examine
how classes in the base class
can be overridden.
Establish how overridden
base class member functions
can still be called from a
derived class.
Figure 124
Step 2
The program has a base class M a m m a l and a
derived class C a t .
The base class has overloaded functions m o v e s ( )
and m o v e s ( 4 ) .
The derived class also has function m o v e s ( ) .
When an instance of C a t is created and the
function m o v e s ( ) called this overrides both of the
overloaded m o v e s ( ) functions in the base class.
There appears to be no way that a C a t object can
get access to the overloaded base class function
moves(int).
Step 3
In m a i n . c p p change the statement
M y C a t . m o v e s ( ) ; to M y C a t . m o v e s ( 4 ) ;
This would appear to a reasonable thing to do as
you want to pass an argument to a base class
member function and there is no matching
function in the derived class.
However, you will get a compilation error. An
overriding method in the derived class will hide all
overloaded methods with the same name in the
base class. Therefore m o v e s ( i n t ) is hidden to
any object of the derived class C a t .
Step 4
Examine the statement
M y C a t . M a m m a l : : m o v e s ( 4 ) ; Here we are
calling the base class function m o v e s ( 4 ) by
explicitly stating the instance, base class name
then member function separated by the : : s c o p e
operator.
We commonly call base class methods in this way
when they have been overridden by derived class
methods.
Task 1 Step 1
Create a new project, call it Create a new project, call it H u m P l a c M a m m a l
HumPlacMammal.
.
You will need to create
three . c p p class files and
then complete the detail Step 2
member function From the directory where you unpacked the
implementation. source materials, open the file called Hum
You will need one H u m a n , P l a c M a m m a l ( S t u d D e f i n i t i o n s ) . There are four
one P l a c e n t a l M a m m a l files you will need.
and a M a m m a l class. The Add all four files to the project you have just
class definitions have been created.
created for you.
Using the skeleton
framework in m a i n ( ) add Step 3
instance and member There are three . h header files showing the
functions calls for each of interfaces for the three classes shown in the
the three classes. hierarchy in Figure 117.
Many member functions Classes we are using are H u m a n , P l a c e n t a l
are overridden and you may M a m m a l and M a m m a l .
have to call base class The Human class is derived from Placental
member functions directly. Mammal and this derived from Mammal.
There is a framework for the m a i n function file.
This contains the main structure for the program.
No objects have been created and there are no
member function calls, this is for you to
implement.
Figure 125
Step 4
Examine Figure 125. This shows how the program
should look when it is run.
An object of the H u m a n class is created and
functions in all three classes called to obtain the
output.
Some of the methods in the classes are overloaded
and some are overridden.
All the output in double quotes i.e. " w a l k e r e c t
o n t w o f e e t " has been returned from member
functions of one of the classes.
Step 5
Using the three interface files to guide you, create
three source code files (. c p p ) to implement
member function functionality.
Step 6
Using the m a i n function file create an instance of
the H u m a n class. Call the member functions of
this object to create an output similar to that
shown in Figure 125.
You will have to override some of the base class
methods and some base class methods you will
have to call directly.
Task 1 Step 1
In eclipse, open the Open F r i e n d s F u n c t i o n project, compile and run
project FriendsFunction the program. The output should be as shown in
. Figure 126.
Examine how a function can
be used to access private and
protected data members of a
class.
Figure 126
Step 2
Open the file m a i n . c p p .
Before m a i n ( ) there is a function prototype.
Rectangle duplicate (Rectangle inrect);
The prototype name is duplicate, it accepts a
Rectangle object as an argument and returns a
Rectangle object.
Step 3
Examine the statement R e c t a n g l e r e c t ( 2 , 3 ) ;
Here we are creating an instance of R e c t a n g l e
class and initialising the data members width (2)
and height (3).
Beneath this a second Rectangle object is created
R e c t a n g l e r e c t b ; using the default constructor.
The next statement of interest is r e c t b =
d u p l i c a t e ( r e c t ) ; Here we are calling the
function duplicate and passing the object r e c t .
This object has data members w i d t h (2) and
h e i g h t (3).
Step 4
Examine the R e c t a n g l e function
Rectangle duplicate (Rectangle inrect)
{
Rectangle rect;
rect.width = inrect.width*2;
rect.height = inrect.height*2;
return (rect);
}
Inside the function a new R e c t a n g l e object is
created, Rectangle rect; The data members of
the object i n r e c t are accessed, doubled, then
assigned to the new object i n r e c t . This is unusual
as p r i v a t e and p r o t e c t e d members of a class
cannot normally be accessed from outside the
same class in which they are declared.
Step 5
Open r e c t a n g l e . h . Note that in the public
section of the class definition the function
d u p l i c a t e has been declared as friend of the
Rectangle class, f r i e n d R e c t a n g l e d u p l i c a t e
(Rectangle);
Declaring a prototype of the external function
within the Rectangle class, then preceding it with
the keyword f r i e n d , means the function can
access the private and public members of the
class.
Task 1
Modify the program in the
F r i e n d s F u n c t i o n project
by adding a new class
T r i a n g l e . Add a definition
and source file. The data
members are b a s e and
height.
Add a constructor,
destructor and member
functions to set the data
members and get the area.
Add another f r i e n d function
and prototype to m a i n ( ) .
Call the function t r i a n g l e .
The area of a triangle can be
calculated as half the base
multiplied by the height.
Add an additional function
prototype to the t r i a n g l e
header file.
Output the area of the new
t r i a n g l e object using the
f r i e n d function to access
the p r i v a t e data members
of the class.
Add an additional function
prototype to the t r i a n g l e
header file.
Task 1 Step 1
In eclipse, open the Open m a i n . c p p and examine the statements
project FriendClass. shown in Figure 127.
Examine how to define a
class as friend of another
class.
The second class (the friend
class) can then be granted
access to the protected and
private members of the first
class. Figure 127
Here we are creating two instance objects, one
R e c t a n g l e and one S q u a r e .
Instance s q r uses the member function
s e t S i d e ( 4 ) to set the dimension of the square.
Instance r e c t calls the c o n v e r t member function
and passes the object s q r .
Step 2
Open s q u a r e . h . Examine the statement:
friend class Rectangle;
This statement declares class R e c t a n g l e as a
friend of S q u a r e . R e c t a n g l e can now access
private and protected data members of instances
of the S q u a r e class.
N o t e : Friendship is one way.
R e c t a n g l e is a friend of S q u a r e and has access
to private and protected data members of the
Square class, but Square objects do not have
access to private and protected data members of
the Rectangle class.
N o t e : Frienships are not transitive. You cannot
have a class as a friend of another friend class
unless explicitly specified.
Step 3
Open r e c t a n g l e . c p p and examine the function
shown in Figure 128.
Figure 128
Function c o n v e r t is passed a parameter of type
Square (a).
In the statement width = a.side *2; a is the
o b j e c t and s i d e is the d a t a m e m b e r of the class
Square.
So the p r i v a t e data members (s i d e ) in class
S q u a r e have been accessed by public member
functions of the R e c t a n g l e class. These have
been assigned to the p r i v a t e data members of the
R e c t a n g l e class, w i d t h and h e i g h t .
When the R e c t a n g l e member function
r e c t . a r e a ( ) is called, the width and height of the
S q u a r e object are used to calculate the area of the
rectangle.
Step 4
Open r e c t a n g l e . h . Notice at the top of the file
the statement #include "square.h". This is
included as we make reference to the S q u a r e
class in the function c o n v e r t ( ) .
Comment out the # i n c l u d e directive and see
what happens when you re-compile.
Task 1 Step 1
Expand the program used in Create two new files, triangle.h and triangle.cpp.
Exercise 48.
Create a new class
Triangle.
Add a function definition
and source code file.
The class will have data
members w i d t h and h e i g h t
and a member function
g e t A r e a ( ) returning the
area of a triangle.
The area of the triangle can
be calculated as ½ the width
*height. The w i d t h and
h e i g h t are the p r i v a t e data
members of the R e c t a n g l e
class.
Do these calculations in a
function in T r i a n g l e that
can be called from m a i n ( ) .
Class T r i a n g l e will have to
be declared as a friend of
Rectangle.
The t r i a n g l e . h file will
need to make a pre-
processor reference to
Rectangle as Rectangle
objects are used in the class
definition.
15.9. Composition
We have already seen that classes can be derived from other classes that provide
attributes and behaviours the new classes can use (i n h e r i t a n c e ). When we
include class objects as members of other classes we call it c o m p o s i t i o n or
aggregation.
A simple definition of composition is; defining a class as a member of another
class.
All normal scope rules then apply. Note however that a class that is a member of
another class does not enjoy the same benefits as a derived class, and only has
access to p u b l i c members of the containing class.
In previous exercises we have seen how to pass arguments to the constructor of a
class when an object is created.
In the following exercises we will pass r e f e r e n c e s to instance objects to a class
constructor and assign these objects to the data members of the class.
Whether we use inheritance or composition in our programs is much discussed.
Google “inheritance V composition”, and see what you get. It can make
interesting reading.
An objective view might be, use composition where you can unless inheritance
will really benefit the design of the program.
Task 1 Step 1
In eclipse, open the Compile and run the program. The program
project Composition. should look the same as Figure 129.
Examine the code to see how
D a t e class objects are used
as data members of the
E m p l o y e e class.
Figure 129
Step 2
Open m a i n . c p p and examine the statements
shown in Figure 130.
Figure 130
The first two statements create two D a t e objects
b i r t h and h i r e . Parameters are passed to the
class constructor to initialise the data members.
The third and fourth statements create two string
objects and initialise them.
The fifth statement creates an instance of class
E m p l o y e e called s t a f f and passes the employee
first and last names and the two D a t e class
objects to the class constructor.
The seventh statement calls the p r i n t method
using the s t a f f object.
Step 3
Open E m p l o y e e . h class definition. This is
shown in Figure 131.
The first statement is the class constructor.
Two s t r i n g s are being passed to the constructor
representing the first and last names.
C o n s t D a t e & is passing a reference to the D a t e
object for the DOB. The D a t e object is c o n s t and
cannot be changed and represents the birth date.
C o n s t D a t e & is repeated (for the date hired)
and the reference is passed to the data member for
hireDate.
Figure 131
Step 4
Examine the two statements:
const Date &birthDate;
const Date &hireDate;
Both are constant references to data member
objects of the class D a t e .
Note the use of # i n c l u d e " D a t e . h " in the
E m p l o y e e class definition.
The E m p l o y e e class is using objects of the class
D a t e so must include the D a t e class definition.
Doing this means the compiler knows about the
D a t e class when the objects are passed via the
constructor in E m p l o y e e . c p p to the D a t e
constructor.
Step 5
Open E m p l o y e e . c p p . Examine Figure 132.
This shows the class constructor using a m e m b e r
i n i t i a l i s e r l i s t to pass initialiser reference values
to the D a t e member objects b i r t h D a t e and
h i r e D a t e in Employee class.
Each of the two object arguments has associated
data members, how do they get initialised?
Fortunately for us we do not have to get involved
in the technicalities of ensuring object data
members are initialised properly.
The compiler provides each class with a default
copy constructor that copies each member of the
constructors argument object into the
corresponding member of the object being
initialised.
Figure 132
Step 6
Examine the code shown in Figure 133, the
h i r e D a t e . p r i n t ( ) ; statement.
The instance object h i r e D a t e is a reference to the
instance (h i r e ) passed from main to Employee.
The reference is used in the member initialiser list
(d a t e O f H i r e ) to initialise the member object
h i r e D a t e , hireDate(dateOfHire).
hireDate.print(); calls the D a t e member
function p r i n t ( ) of the instance h i r e of the D a t e
class.
The p r i n t ( ) function of the D a t e class object
outputs the date the employee was hired.
Ina similar way birthDate.print(); calls the
D a t e member function p r i n t ( ) of the instance
b i r t h of the D a t e class.
Figure 133
Task 1
Create a new project, call it
Students.
You need to maintain a
record of students on your
course.
Get the user to add records
for 3 new students. The
fields required are:
Name;
dateOfBirth;
dateOfEnrolment;
courseName;
Figure 134
Create instances of the class
S t u d e n t and store these in
a vector.
Use vector member
functions to add each
student object.
Use the Date class files from
Exercise 50 to store and
print dates.
The output should provide a
list of names with student
DOB, course name and the
date they enrolled on the
course, see Figure 135.
Figure 135
Task 1
Create a new project, call it
ATM Screen.
You will need to create three
classes, A T M , S c r e e n &
Keypad.
Figure 136 shows a class
diagram with composition of
classes.
A T M is using objects of class
S c r e e n and K e y p a d as
members. Class A T M has a
composition relationship
with class S c r e e n and
Keypad. Figure 136
A member function of the
S c r e e n class is used to
output prompts to screen
and a member function of
K e y p a d used to get user
input.
In the m a i n ( ) function
create an instance of the
ATM class.
The A T M class should
define a S c r e e n & K e y p a d
object as private members of Figure 137
the A T M class.
Use member functions of
S c r e e n class to output user
information. All input
should be via K e y p a d class
member functions.
Verify the account and PIN
numbers read in are valid
using member functions of
class A T M .
If they are not valid inform
the user, see Figure 137.
If they are valid provide a Figure 138
menu similar to that shown
in Figure 138 using S c r e e n
member functions.
The menu does not need to
have any functionality yet.
16 Operator Overloading
One of the nice features of C++ is that you can give special meanings to
o p e r a t o r s when they are used with user defined classes. This is not something
you can do in all object oriented programming languages and notably this
functionality is not available in Java or C#.
The process of giving special meanings to operators is called o p e r a t o r
o v e r l o a d i n g . In C++ we implement overloading by providing special member-
functions on classes and these must follow a particular naming convention.
For example, to overload the addition operator + for your class you would provide
a member-function named operator+ for the class.
To overload the stream insertion operator < < for your class you would provide a
member-function named operator<< for the class.
All the operators we have used so far (and many more) can be overloaded and
there are very few that cannot be. The exceptions from those used so far are: ( . )
member selection and (: : ) scope resolution operators.
There are some important things to consider in operator overloading. Operator
overloading adds new functionality to existing operators. It is important that
comments explaining the new functionality of the overloaded operator are added
to your code. In the simple examples we use in this section it is relatively easy to
work out how the programs work. With more complex programs this will be
difficult.
Only use overloading when really necessary.
Task 1 Step 1
In eclipse, open the Open m a i n C o m p l e x . c p p . Run the program and
project Operator see how it works.
Overloading plus.
Examine how to overload
the addition + operator.
Figure 139
Examine the code shown in Figure 147.
Here we are creating four objects of the C V e c t o r
class and initialising three of the first four objects.
Step 2
Figure 140
Examine the statement shown in Figure 140. At
first glance this seems to be using the addition
operator to add two instance objects and assigning
the result to d .
This is not possible and shows why operator
overloading can become confusing. The + operator
is overloaded and we will need to examine the class
implementation file in the next step to see how this
works.
Note that d = a ; the copy assignment operator is
the only operator member function implemented
by default. Object d becomes a copy object a .
Comment out the line shown in Figure 140 and add
d = a; in it’s place. Run the program and see
what happens.
When you have done this reinstate the statement
shown in Figure 140 and delete d = a;
Step 3
Open c o m p l e x . c p p .
Figure 141
Examine the function named o p e r a t o r + shown in
Figure 141.
o p e r a t o r + indicates the + addition operator is
being overloaded.
Step 4
Examine the function o p e r a t o r + .
The function o p e r a t o r + shown in Figure 141 is
used to overload the + operator to add two complex
numbers.
Task 2
Modify the program to sum
the three C V e c t o r instance
object data members.
Compile and run the
program and explain what
is happening.
Task 1 Step 1
In eclipse, open the Open m a i n . c p p . Run the program and see how it
project Overload works. The output should be the same as Figure
Stream Insertion. 142.
Examine how to overload
the stream operators.
Figure 142
Figure 143
Step 2
Examine the code shown in Figure 143. Two
objects of the class P a r t N u m b e r have been
created, p a r t and p a r t 2 .
The statement c i n > > p a r t is passing the i s t r e a m
object c i n and the instance object p a r t to the
overloaded function o p e r a t o r > > .
The statement c o u t < < p a r t is passing the
o s t r e a m object c o u t and the instance object p a r t
to the overloaded function o p e r a t o r < < .
Figure 144
Step 3
Open the implementation file S p a r e P a r t s . c p p
and examine the code shown in Figure 144.
The overloaded o p e r a t o r > > function returns a
reference to an i s t r e a m object and takes two
parameters by reference:
These are an i s t r e a m object and a user-defined
type.
The user-defined type 'P a r t N u m b e r ' is not passed
as a c o n s t parameter because the input operation
can modify it.
The body of the overloaded o p e r a t o r > > function
assigns members of the user-defined object to the
instance data members.
Figure 145
Step 4
Examine the code shown in Figure 145 of the
implementation file S p a r e P a r t s . c p p
The overloaded o p e r a t o r < < function returns a
reference to an o s t r e a m object and takes two
parameters by reference:
These are an o s t r e a m object and a user-defined
type.
The user-defined type 'p a r t N u m b e r ' is passed as a
c o n s t parameter because the output operation
doesn't modify it.
The body of the overloaded o p e r a t o r < < function
inserts members of the user-defined object into the
o s t r e a m object.
Figure 146
Step 5
Open the definition file S p a r e P a r t s . h and
examine the code shown in Figure 146.
The two overloaded input and output operator
functions are declared as f r i e n d s because they
need to access non-public (private and protected)
class data members (M a n u f a c t u r e r etc) directly
as the class does not have any get member
functions.
The two overloaded functions are not part of the
class P a r t N u m b e r but added as prototypes of the
external functions within the class definition in
SpareParts.h.
See section 15.7 for more information on friend
functions.
Task 1 Step 1
In eclipse, open the Open I n h e r i t a n c e M a i n . c p p .
project Inheritance
Dynamic
Examine how to
dynamically allocate
memory for a C a t object.
Learn how to use pointers
and pointer notation to Figure 147
access member functions.
Examine the code shown in Figure 147.
Learn how to dynamically
The first statement creates a pointer p t r C a t that
allocate and delete
will point to a C a t object.
memory.
The second statement dynamically allocates the
memory for the Cat object. The default constructor
is called and the string argument passed. A pointer
to the object memory location is returned.
Step 2
Examine the two statements shown in Figure 148.
Figure 148
The first statement uses the pointer p t r C a t and the
arrow notation to point to the member function
s e t A g e ( ) . A parameter 5 is passed. This sets the
data member a g e in the base class to 5.
The second statement uses the pointer and arrow
notation to set the data member w e i g h t in the
base class.
Note how similar pointer notation is used to access
other member functions.
Step 3
Examine the statement delete ptrCat; This
statement frees the memory dynamically allocated
with n e w .
Task 1 Step 1
Using the I n h e r i t a n c e Open I n h e r i t a n c e M a i n . c p p .
D y n a m i c project from
Add the code to create a dynamic array of cats.
Exercise 55 add a dynamic
array to add two additional Remember to take care when using pointers to loop
Cat objects. through the array or the address of the beginning
of the array may be lost.
Step 2
Output the names and other details of the new cats.
The output should be similar to that shown in
Figure 149.
Figure 149
Step 3
Remember to free the memory. See start of section
16.
Task 1 Step 1
In eclipse, open the Open the project s t r c a t S t r n c a t and run the
project strcatStrncat. program. Add your name when prompted. The
Examine the use of string output should be as shown in Figure 150.
manipulation functions
Figure 150
Step 2
Examine the statements shown in Figure 151.
Figure 151
The first statement declaration creates an array, a
to hold 28 characters including the null character
‘\0’.
The next three statements create character arrays
to hold 25, 25 and 60 characters including null
characters.
char *Ptr; declares a pointer to a character. This
will be used to point to the start of one of the
arrays.
Step 3
The statement in Figure 152 uses the string
manipulation function g e t l i n e ( ) . g e t l i n e ( ) will
read into the array 25-1 characters.
The ending n u l l c h a r a c t e r is automatically
appended after the data stored in b.
Figure 152
Step 4
Examine the statement shown in Figure 153.
Figure 153
This function is similar to r e p l a c e ( ) in string
class. strcpy(c, b); copies the contents of array
b into array c including the null character.
Step 5
The statements shown in Figure 154 is similar to
s t r c p y ( ) but only copies a specified number of
characters, the first 3 characters of b into c.
Note that strncpy(c, b, 3); does not copy the
null character, this has to be done separately.
c[3] = '\0'; appends ' \ 0 ' to c's contents at
element number 4.
Figure 154
Step 6
Examine the statement shown in Figure 155.
Figure 155
P t r is a pointer to type char, declared at the start of
the program.
A pointer is assigned by s t r t o k to P t r and points to
the first character in the array a . s t r t o k then takes
the next delimiting character specified here as “ “
(space) and replaces it with null char ' \ n '
terminating the first token.
Here is the fancy bit. s t r t o k saves (s t a t i c v a r ) a
pointer to the next character following the token in
array a and returns a pointer to the current token.
Step 7
Examine the code shown in Figure 156. The while
loop is used to continuously call s t r t o k .
Subsequent calls to s t r t o k have N U L L as the first
argument.
The N U L L argument indicates s t r t o k should
tokenise from the saved pointer location in array a .
When there are no tokens remaining s t r t o k
returns N U L L .
NOTE: s t r t o k modifies the input string replacing
each delimiter with the null char ' \ n ' . The original
string will be truncated to the first word in the
array.
To avoid losing the contents of the array, copy the
original string into another array before tokenising.
Figure 156
Task 2
Explain why the last
statement shown in Figure
150 shows the array
containing just the word
Welcome.
Task 1 Step 1
Copy your folder c o n s t c h a r * c o n s t , signifies a constant pointer to
C o m p o s i t i o n from constant data.
Exercise 50 and save it as
The class implementation file (. c p p ) should use
CompCString.
functions:
Modify the program to use
s t r l e n to get the length of the strings read and,
pointer based strings.
s t r n c p y to copy the characters read in to the two
The changes to the class
arrays, up to a maximum declared in the header
definition (. h ) file are
file. See Figure 157 for the character array sizes.
shown in Figure 157.
Figure 157
Task 1 Step 1
From the directory Using the program in Exercise 57 as a guide
where you unpacked initialise an array with the data in the Java.txt file.
the source materials,
open the file called Jav The program should allow the user to search for a
a.txt. user input word.
The text file contains a We also need to establish the following:
paragraph of text that we Number of characters in the complete paragraph.
need to analyse.
Number of characters (no spaces) in the paragraph.
Number of sentences in the paragraph.
The number of words each sentence contains.
You will need to tokenise the text using different
criteria.
The output should be similar to that shown in
Figure 158.
Figure 158
19 Polymorphism
In most of our programs so far we have been using inheritance where derived
classes inherit the data members of the base class. We have seen that a derived
class object is a kind of base class object.
One of the key features of a derived class is that a pointer to a derived class is
type-compatible with a pointer to its base class. Polymorphism is the art of taking
advantage of this simple powerful and versatile feature by using v i r t u a l functions
and b a s e class pointers
Polymorphism refers to an objects ability to respond in an individual manner to
the same message. With polymorphism one function can cause different actions
to occur depending on the type of object where the function is invoked.
Polymorphism occurs when a program invokes a v i r t u a l function through a
b a s e c l a s s p o i n t e r or r e f e r e n c e . C++ dynamically chooses the correct
function for the class from which the object was instantiated.
In C++ a virtual function is a member function of a b a s e class. Its functionality
can be over-ridden in its d e r i v e d classes and the whole function body replaced
with a new set of implementation in the d e r i v e d class.
Consider the class structure shown in Figure 159. Pigeon and Duck both inherit
from class Bird. Pigeon and Duck are derived classes.
Figure 159
There are features that are unique to Pigeons and features that are unique to
Ducks. These can be stored in data members of the class and accessed via the
member functions.
There are also features that are shared by the two classes. With a little
imagination we can consider two, both objects fly and walk. We will create two
member functions that are common to both classes, f l y ( ) and w a l k ().
With polymorphism one function can cause different actions to occur depending
on the type of object where the function is invoked. As we are going to refer to
members of the derived classes using a b a s e c l a s s p o i n t e r , we need all three
classes to have f l y and w a l k functions.
The secret to using polymorphism in C++ is to create a v i r t u a l member function
in the base class. Its functionality can be over-ridden in its derived classes using
functions with the same name as the virtual function. The whole function body is
replaced with a new set of implementation in the derived class.
19.1. Polymorphism
Task 1 Step 1
In eclipse, open the I n e c l i p s e , o p e n t h e p r o j e c t B i r d s . Compile
project Birds. and run the program.
Examine how a pointer to a The output should be the same as that shown in
base class is type- Figure 160.
compatible with a pointer
to a derived class. The output shows how by using a b a s e class
pointer and assigning a r e f e r e n c e to a derived
Understand how v i r t u a l class object it is possible to access the member
member functions used in a functions of the derived class.
b a s e class can have their
functionality over-ridden in It also shows how by using v i r t u a l functions and
the d e r i v e d classes. polymorphism it is possible for a virtual base class
member function to be over-ridden by any virtual
The whole function body in function in the derived classes with the same name.
the base class can be
replaced with a new set of As both derived classes have t a l k ( ) functions and
implementation in the t a l k ( ) is a v i r t u a l function in the base class then
derived class. the derived class t a l k ( ) functions will override the
base class function.
Figure 160
Step 2
Open m a i n . c p p . Examine the statements shown
in Figure 161.
Figure 161
Duck myDuck; creates an object of type D u c k
called m y D u c k .
The next statement creates a b a s e c l a s s pointer
P t r b of type B i r d . Assigned to the base class
pointer is a reference to a D u c k object, m y D u c k .
It is now possible to use polymorphism to invoke a
v i r t u a l function in a derived class through a base
class p o i n t e r or r e f e r e n c e .
C++ dynamically selects the correct virtual
function in the derived class using the r e f e r e n c e
object assigned to the b a s e class pointer.
The v i r t u a l function functionality in the base class
is over-ridden by that in the derived class and the
whole base class function body replaced with a new
set of implementation defined in the derived class.
Step 3
Open the base class definition b i r d . h . Examine
the statements shown in Figure 162.
Figure 162
The first statement is the class constructor.
The second statement is the class destructor.
Notice the class destructor is v i r t u a l . When the
base class destructor is declared as virtual, both
destructors (base and derived will be executed).
If virtual is omitted only the base destructor will be
executed.
A good rule of thumb is to include a destructor and
declare it as virtual if there are any virtual member
functions. This will ensure any destructors in
derived classes are executed.
The third statement defines a standard member
function w a l k ( ) .
Step 4
Open the base class implementation file b i r d . c p p .
Examine the code shown in Figure 163.
There is a class constructor, a destructor and two
member functions.
The base class functions are w a l k ( ) and the
v i r t u a l function t a l k ( ) .
The t a l k ( ) function in this base class will be
overridden by the t a l k ( ) functions in the derived
classes P i g e o n and D u c k with the same name.
The derived class function called is determined by
type of object (Duck or Pigeon) the base class
pointer is addressing.
Figure 163
Step 5
Open the D u c k class definition file d u c k . h .
Examine the code shown in Figure 164.
Figure 164
The first statement declares a function to override
the base class function talk().
N o t e : It is not strictly necessary to add v i r t u a l to
derived virtual methods but it is considered good
practice. Doing so makes it obvious what the
function does.
The second statement declares a method that could
override the base class function w a l k ( ) .
However, the function w a l k ( ) will not override the
base class function. With polymorphism a base
class pointer must be used to point to the derived
instance.
The base class pointer does reference a D u c k
object, but w a l k ( ) is not a virtual function
therefore the base class function w a l k ( ) will always
be called.
Only member functions that are v i r t u a l will be
overridden by the derived class function. Function
w a l k ( ) is not a virtual function so the pointer will
use the base class function w a l k ( ) .
Step 6
Open the Duck class implementation file
duck.cpp. Examine the code shown in Figure 165
The two functions are t a l k ( ) , the v i r t u a l function
that will override the base class function and
walk().
Derived class w a l k ( ) can not be called as the base
class pointer (P t r b ) used to access the member
functions cannot be used to access a non-virtual
member function.
Figure 165
Step 7
Examine p i g e o n . h function definition and
p i g e o n . c p p the implementation file.
These derived class member functions work in a
similar way to the derived class D u c k described in
Exercise 60 Exercise 60Task 1.
Task 1
Using the project from the
previous exercise, Exercise
60 modify the program to
output the data contained
in the derived class member
functions w a l k ( ) .
There are two ways to do
this.
Firstly it is possible to make
the w a l k ( ) functions
v i r t u a l . Try this, ensuring
you can access the derived
class member functions and
get the expected output.
Secondly, and this is a good
bit trickier. Examine the
statements shown in Figure
161. Remember the pointer
is of type B i r d . This is a
base class pointer and by
using this base class pointer
and v i r t u a l functions we
can gain access to derived
member functions that are
also v i r t u a l .
Task 1 Step 1
In eclipse, open the Run the program.
project Polygon.
The output should be as shown in Figure 166.
Modify the program.
Figure 166
Step 2
Modify the program so that the base class pointers
of type Polygon can be used to access all the
area() member functions of all class objects.
We do not want to access the objects directly
(object.method) as r e c t . a r e a ( ) and t r g l . a r e a ( ) .
20 Session 3
20.1. files used
21 Abstract Classes
All the programs we have created so far have been made up of classes. From
these classes we have created objects of the class. There are occasions when it is
useful to create classes from which we never intend to create instance objects.
These are a b s t r a c t classes.
A b s t r a c t classes are usually used as b a s e classes. Abstract classes can never be
instantiated and require the derived classes to complete the class before
instantiation.
If there is an a b s t r a c t class then there is a good chance there is also a c o n c r e t e
class. This is the name given to the classes you have created so far; classes that
can be instantiated are called concrete classes.
We can create an a b s t r a c t class S h a p e and then derive concrete classes with
the specific detail necessary to instantiate an object. The concrete classes might
be C i r c l e , S q u a r e and T r i a n g l e . Figure 167 shows a primitive inheritance
hierarchy for shapes.
Figure 167
In Figure 167 we can define S h a p e as an a b s t r a c t class. It would be extremely
difficult to define the data members and member functions for a s h a p e class.
How do you draw a shape? What kind of shape? What attributes does the shape
have?
These are reasonable questions but questions that we cannot answer without
more detail. To help answer the question we make the class abstract and then
add the specifics in the concrete classes C i r c l e , R e c t a n g l e and T r i a n g l e .
To create an abstract function we need to make one of its v i r t u a l functions a
p u r e v i r t u a l function by placing “= 0 ” in the declaration. This is known as the
pure specifier.
virtual void area() const = 0;
When we use abstract classes the concrete derived classes must override all base
class virtual functions with concrete implementations of the abstract class
functions.
So what is the difference between a virtual function and a pure virtual function?
A virtual function has implementation in the function and the derived class has
the option of overriding the function.
A pure virtual function provides no implementation and needs the derived class
to override it with any implementation. An abstract class cannot be instantiated
and simply declares common attributes and behaviours.
Task 1 Step 1
In eclipse, open the In eclipse, open the project PureVirtual.
project PureVirtualFun Compile and run the program. The output should
ctions. be the same as that shown in Figure 168.
Examine the program to This program allows us to create two members of
establish how to create an staff. Salaried and Hourly paid. There is a base
a b s t r a c t class. class Employee and two derived classes Salaried
Understand how to create a and Hourly.
p u r e v i r t u a l function and The output for each of the two instance objects
understand the difference appears twice to demonstrate the use of s t a t i c and
between a v i r t u a l function d y n a m i c binding.
and p u r e v i r t u a l function.
You will also be introduced
to s t a t i c and d y n a m i c
binding.
Figure 168
Step 2
Open m a i n . c p p . Examine the statements shown
in Figure 169.
Figure 169
This is a function prototype receiving a constant
pointer to a constant object, base class o b j e c t
Employee.
This is the prototype for the function used to call
the derived class functions using polymorphism
and dynamic binding.
Step 3
Examine the statements shown in Figure 170. The
first statement creates an instance s E m p l o y e e of
class S a l a r i e d and initialises the data members
via the constructor.
The second statement creates an instance
h E m p l o y e e of class H o u r l y and initialises the
data members via the constructor.
Figure 170
Step 4
Examine the statements shown in Figure 171. The
statement s E m p l o y e e . p r i n t ( ) is using the dot
member-selection operator “object.method()”.
This means the compiler can identify (knows
about) each object (s E m p l o y e e and h E m p l o y e e )
at compile time and knows which p r i n t and
e a r n i n g s functions to call. This is s t a t i c
binding.
Figure 171
Step 5
Examine the statements shown in Figure 172.
Figure 172
In this statement we create a vector to hold
p o i n t e r s of type E m p l o y e e class. The vector has
an initial size of two elements.
Step 6
Examine the statements shown in Figure 173.
Figure 173
Here the vector is initialised with addresses of
S a l a r i e d Employees and H o u r l y paid Employees.
The addresses are stored in base class E m p l o y e e
pointers.
This is possible as a pointer to a derived class is
type-compatible with a pointer to its base class.
This is polymorphism.
Step 7
Examine the statements shown in Figure 174. The
f o r loop lets us loop through the vector elements
and pass the address of each object to the function
virtualPointer.
Figure 174
Step 8
Examine the statements shown in Figure 175.
Both statements are used to access virtual
functions.
The first statement calls the p r i n t ( ) function using
the base class (E m p l o y e e ) pointer and the arrow
notation (- > ). This calls the derived class p r i n t ( )
function.
Figure 175
Task 1 Step 1
Create a new project, call it Using the hierarchy shown in Figure 167 create an
Shapes. abstract class S h a p e with no implementation.
Step 2
Create three derived classes, P a r a l l e l o g r a m ,
R e c t a n g l e and T r i a n g l e . You will need two data
members for each object, width (base) and height.
Set these using class constructors when the objects
are created.
Step 3
Output the area of each object using polymorphism
and dynamic binding.
Task 1 Step 1
In eclipse, open the Open A T M . c p p .
project Student ATM
Abstract Balance Examine the statement:
Inquiry Transaction * transactionPtr;
This statement creates a b a s e class pointer
(t r a n s a c t i o n P t r ) to the T r a n s a c t i o n class.
Transaction is an a b s t r a c t class and a class that
we will never instantiate any objects from.
The class is used to declare the common attributes
and behaviours for its derived classes
B a l a n c e I n q u i r y , D e p o s i t and W i t h d r a w a l .
See Figure 176.
Note the common behaviour for the derived classes
is r u n ( ) .
Figure 176
Step 2
Examine the statement:
transactionPtr =
createTransaction(selection);
c r e a t e T r a n s a c t i o n ( ) is a p r i v a t e u t i l i t y
f u n c t i o n and can only be accessed from within the
class.
s e l e c t i o n is the user input choice from the menu
(1-4). c r e a t e T r a n s a c t i o n returns a pointer of
type determined by the user input (1-4).
Figure 177
Step 3
Examine the c r e a t e T r a n s a c t i o n ( ) function
shown in Figure 177.
The function receives an integer (user input) that
corresponds to the action the user wants to take,
B a l a n c e I n q u i r y , W i t h d r a w a l or D e p o s i t .
Case select option 3 (D e p o s i t ) is not functional
just yet so there is a prompt to let the user know.
If the user inputs a 1 , a B a l a n c e I n q u i r y object is
dynamically created and assigned to a base class
pointer t e m p P t r .
Similarly if the user inputs a 2 , a W i t h d r a w a l
object is dynamically created and assigned to the
base class pointer t e m p P t r .
The base class pointer is returned to the calling
function and assigned to another base class
pointer, see Figure 178.
Figure 178
Step 4
Examine the statement shown in Figure 179.
Figure 179
Task 2
Create a new class D e p o s i t
and add the necessary
functionality to present the
user with sufficient
information to let them
know they have called the
relevant functions in the
Deposit class.
Inform the user from
within the class that you
will be continuing to
develop the O U C S A T M .
Task 1
Using the class diagram
shown in Figure 181 create
additional classes to
provide more functionality
to the OUCS ATM.
Add functionality to check
balance, make withdrawals
and deposits.
The interface should be
similar to Figure 180.
Figure 180
23.1. Containers
Vector, deque and list are three STL containers. They are more correctly called
f i r s t - c l a s s c o n t a i n e r s . Other containers are called a d a p t e r s and n e a r
c o n t a i n e r s . Pointer based arrays, string, bitsets and valarrays are near
containers, we will not be looking at those in this session.
sequence containers
vector
lists
deque
Table 8
associative containers
set
multiset
map
multimap
Table 9
It is not efficient to insert or delete elements in the middle of the vector as the
entire vector must be moved as vector elements must occupy contiguous cells in
memory.
It is possible to insert elements anywhere in a vector but other containers are
better suited to this, notably the deque and list.
If we need to add or delete data from both ends of a container the deque would be
a good choice.
Again both containers (deque and list and even the vector) can do the job but the
deque is more efficient with insertions and deletions from the front.
If we need to make insertions and deletions at the start, or end or anywhere else
in the container then the list would be most efficient.
All STL containers provide similar functionality and as we would expect, each
container has associated member functions. A subset of these member functions
is common to all containers i.e. s i z e ( ) .
s i z e ( ) member function will return the number of elements of any container
type it is used with.
23.3. Algorithms
The STL provides many standard algorithms that can be used generically across a
variety of containers.
The header < a l g o r i t h m > defines a collection of functions especially designed to
be used on ranges of elements.
Algorithms are global functions that operate with iterators. Often one algorithm
can operate on elements of different container types. It is also possible to use
algorithms for user-defined container types and arrays.
These algorithms offer general fundamental services, such as searching, sorting,
copying, reordering, modifying, and numeric processing. Understanding what
algorithms can be used with which containers takes time to learn.
However, learning the algorithms you can use with selected containers will save
time in the long run as there is no need for you to develop your own algorithms
with so many reusable ones available, see Table 11.
C++ Algorithms
accumulate sum up a range of elements
adjacent_difference compute the differences between adjacent elements in
a range
adjacent_find finds two items adjacent to each other
binary_search determine if an element exists in a certain range
copy copy some range of elements to a new location
copy_backward copy a range of elements in backwards order
count return the number of elements matching a given value
count_if return the number of elements for which a predicate is
true
equal determine if two sets of elements are the same
equal_range search for a range of elements that are all equal to a
certain element
fill assign a range of elements a certain value
fill_n assign a value to some number of elements
find find a value in a given range
find_end find the last sequence of elements in a certain range
find_first_of search for any one of a set of elements
find_if find the first element for which a certain predicate is
true
for_each apply a function to a range of elements
generate saves the result of a function in a range
generate_n saves the result of N applications of a function
includes returns true if one set is a subset of another
inner_product compute the inner product of two ranges of elements
C++ Algorithms
C++ Algorithms
replace_copy_if copy a range of elements, replacing those for which a
predicate is true
replace_if change the values of elements for which a predicate is
true
reverse reverse elements in some range
reverse_copy create a copy of a range that is reversed
rotate move the elements in some range to the left by some
amount
rotate_copy copy and rotate a range of elements
search search for a range of elements
search_n search for N consecutive copies of an element in some
range
set_difference computes the difference between two sets
set_intersection computes the intersection of two sets
set_symmetric_difference computes the symmetric difference between two sets
set_union computes the union of two sets
sort sort a range into ascending order
sort_heap turns a heap into a sorted range of elements
stable_partition divide elements into two groups while preserving their
relative order
stable_sort sort a range of elements while preserving order
between equal elements
swap swap the values of two objects
swap_ranges swaps two ranges of elements
transform applies a function to a range of elements
unique remove consecutive duplicate elements in a range
unique_copy create a copy of some range of elements that contains
no consecutive duplicates
upper_bound searches for the last possible location to insert an
element into an ordered range
Table 11
Certain iterator operations are uniform across all containers. The dereferencing
operator (* ) dereferences an iterator so that you can use the element to which it
points in a similar way to working with pointers.
The + + operation on an iterator moves it to the next element of the container in a
similar way to incrementing a pointer to an array moves the pointer to the next
element.
All STL first-class containers have member functions b e g i n ( ) and e n d ( ) .
b e g i n ( ) returns an iterator pointing to the first element in the container and
e n d ( ) returns an iterator pointing to the first element past the end of the
container.
If we assume an iterator “i t r ” points to the first element of a container, + + i t r
points to the second element and * i t r refers to the element pointed at by i t r .
Note that the iterator resulting from e n d ( ) can only be used in an equality or
inequality comparison to determine whether the iterator “i t r ” has reached the
end of the container. This is because the member function e n d ( ) returns an
iterator that refers to a position past the last element in a container and not the
last element of the container.
Iterator Types
input Used to read an element from a container.
An input operator can only move in a
forward direction (container beginning to
end) one element at a time. Input iterators
support only one-pass algorithms – the
same operator cannot be used to pass
through a sequence twice.
output Used to write an element to a container. An
output iterator can move only in the
forward direction one element at a time.
Output iterators support only one-pass
algorithms – the same output iterator
cannot be used to pass through a sequence
twice.
forward Combines the capabilities of input and
output iterators and retains their position
in the container.
bidirectional Combines the capabilities of a forward
iterator with the ability to move in the
backward direction (from end towards the
beginning). Bidirectional iterators support
multipass algorithms.
random access Combines the capabilities of a bidirectional
iterator with the ability to directly access
any element of the container, to jump
forward or backward by an arbitrary
number of elements.
Table 12
Containers that support random access iterators can use all algorithms in the
STL.
There is an iterator category hierarchy with each category providing a specific set
of functionality. Figure 182 shows the hierarchy. Each iterator category supports
all the functionality of the categories above it.
The bottom category, r a n d o m a c c e s s iterators are the most powerful iterators
having their own functionality together with the functionality of all the categories
above.
As we have mentioned the iterator category that each container supports (see
Table 13) determines whether that container can be used with specific algorithms
in the STL.
Figure 182
Table 13
Iterator operation
All iterators
Iterator operation
Input iterators
*p dereference an iterator
p = p1 assign one operator to another
p == p1 compare iterators for equality
p != p1 compare iterators for inequality
Output iterators
*p dereference an iterator
p = p1 assign one operator to another
Forward iterators forward iterators contain all the functionality of
both input iterators and output iterators
Bidirectional iterators
Table 14
In the example below the s o r t ( ) algorithm is using two iterators pointing to the
start and end of the vector called m y V e c t o r ;
sort (myVector.begin(),myVector.end();
Because s o r t ( ) algorithm uses random-access iterators to the initial and final
positions of the sequence to be sorted, s o r t ( ) can be used with the v e c t o r and
d e q u e containers but not the l i s t container. Lists only support bidirectional
iterators.
However, l i s t containers have a member function s o r t ( ) that can be used to sort
list elements.
Table 13 shows the different iterators supported by each container.
Table 15 shows predefined iterator t y p e d e f s found in the class definitions of the
STL containers.
Table 16 and Table 17 below show the member functions and algorithms available
to each container, v e c t o r , l i s t and d e q u e .
The STL algorithms can also be decoupled from the STL container classes. What
this means to us is that certain algorithms (r e v e r s e is a good example) can be
used to reverse elements in a vector, a list and deque. They can even be used to
reverse elements in C type arrays.
reverse(addresses.begin(),addresses.end());
The reason we can use the r e v e r s e algorithm with the l i s t container is because
r e v e r s e uses bidirectional iterators supported by the l i s t container.
Table 16
Learning to read and write data to file is something that must be learned to make
meaningful use of containers.
Adding data to containers can be a time consuming and tedious process, using
files relieves the boredom of manually adding data before we manipulate our
containers using algorithms and iterators.
In the examples used in the following exercises data is sent to/from file in simple
text format and can easily be read with a text editor. It is also possible to output
and input data in binary format.
C++ imposes no structure on the files we create and with our simple examples of
storing integers, doubles etc this will not be a problem. If we need to store objects
(with several different data members) we will need to structure the file
accordingly. This will be shown in later exercises.
To write to a file we need to add the < f s t r e a m > header file. This allows the use
of o f s t r e a m class instance objects to write data to file as output streams.
The file to be associated with the stream can be specified either as a parameter in
the constructor ofstream outFile( "Numbers.txt", ios::out);when the
instance object o u t F i l e is created.
ofstream outFile;
outFile.open("Numbers.txt", ofstream::out );
i o s : : o u t and o f s t r e a m : : o u t are modes the file will be opened in. In the above
cases o u t denotes writing to file with any existing data in the file being deleted.
Mode i o s : : a p p appends data to the file.
When data has been transferred to file the interface can be closed (or
disassociated) by calling member function c l o s e , outFile.close(); Once
closed, the same file stream object can be used to open another file.
To read from a file the i f s t r e a m class instance objects allow us to read data from
files as input streams.
The file to be associated with the stream can be specified either as a parameter in
the constructor ifstream inFile( "Numbers.txt", ios::in ); in a similar
way as when writing to file.
or by calling member o p e n .
ifstream inFile;
inFile.open("Numbers.txt", ofstream::in );
After all data has been transferred the interface can be closed (or disassociated)
by calling member c l o s e . Once closed, the same file stream object may be used
to open another file.
Task 1 Exercise 68
In eclipse, open Open F i l e I O project and examine the code. Only
the project FileIO the parts that relate to writing to and reading from file
in the I O B a s i c are covered here.
I N _ O U T folder and
examine the code to The < f s t r e a m > header file is included to allow the use
establish how to read of o f s t r e a m and i f s t r e a m classes to create instance
and write files. objects to read and write to and from file.
Exercise 69
ofstream outFile("Numbers.txt", ios::out );
The statement above creates an instance of o f s t r e a m
called o u t F i l e . The ofstream constructor takes two
arguments, the name of the file and how the file should
be opened.
In this example o u t indicates any data in the file will
be overwritten. i o s : : a p p will append any records
written to file.
Passing the file name and mode to the constructor in
this way also opens the file for writing.
N o t e that it is unnecessary to write i o s : : o u t so the
line could have been written o f s t r e a m
outClientFile( "clients.txt") ;
Exercise 70
if (outClientFile.fail())
f a i l ( ) is a member function that the o f s t r e a m object
o u t F i l e inherits.
If for some reason the file cannot be opened for writing
an error message is given and the function e x i t called
and the program terminates.
However it is most unlikely the exit function will be
called as if the file does not exist one is created.
Exercise 71
w h i l e ( c o u n t < i n t S t o r e . s i z e ( ) ) uses a w h i l e loop
to loop through vector i n t S t o r e .
Member function s i z e ( ) gets the number of elements
in the vector to control the while loop outputting each
element to file followed by the return character e n d l .
Step 1
outFile << intStore.at(count)<<endl;
o u t F i l e is the object that points to the file
Numbers.txt.
Each element in the i n t S t o r e vector is passed to file
together with the end of line character using stream
insertion operators < < .
o u t F i l e . c l o s e ( ) ; closes the file.
Step 2
Let’s see how to read from file.
ifstream inFile( "Numbers.txt", ios::in );
The statement above creates an instance of i f s t r e a m
called i n F i l e . The i f s t r e a m constructor takes two
arguments, the name of the file and how the file should
be opened, in this case we are reading i n .
i n F i l e . c l e a r ( ) ; resets e o f for input, though this is
not really necessary here as i n F i l e has just been
created.
i n F i l e . s e e k g ( 0 ) ; positions pointer to beginning of
file, again as we’ve just created i n F i l e , it’s not strictly
necessary.
Step 3
If(inFile.fail())
f a i l ( ) is a member function that the i f s t r e a m object
i n F i l e inherits.
If for some reason the file cannot be opened for
reading (wrong name or no file) an error message is
given and the function e x i t called and the program
terminates.
Step 4
while(!inFile.eof())
{
inFile >> r;
storeSort.push_back(r);
}
The while loop reads the integers input stream object
i n F i l e while not meeting the end of file character.
Each integer is stored in variable r and then pushed
onto the vector s t o r e S o r t .
i n F i l e . c l o s e ( ) ; closes the file.
Step 5
The statement s t o r e S o r t . e r a s e ( s t o r e S o r t . e n d ( ) -
1 ) ; removes the last element of the vector. This is
necessary because after the last record (integer) is
passed to file the end of line character is also passed.
The effect of passing e n d l is to create an additional
record. See the statement below which was used
earlier in the program to pass vector elements to file.
outFile << intStore.at(count)<<endl;
Step 6
s o r t ( s t o r e S o r t . b e g i n ( ) , s t o r e S o r t . e n d ( ) ) ; s o r t is
an algorithm that uses random access iterators.
The s o r t ( ) algorithm sorts the elements in the range
[ s t o r e S o r t . b e g i n ( ) , s t o r e S o r t . e n d ( ) ] into
ascending order with the elements being compared
using a default < (less than) operator.
Step 7
for (int i = 0; i < storeSort.size(); i++)
outputLine(storeSort[i]);
The f o r loop is used to iterate through the vector
passing each element in turn to the function
o u t p u t L i n e where it is output.
A static counter in the function o u t p u t L i n e (not
shown here) is used to add an end of line character and
create a new line after ten integers have been output.
Task 2
Modify the file so when
the program is run
additional records are
appended to the file.
Vectors are a kind of sequence container with their elements ordered following a
strict linear sequence.
Vector containers have their elements stored in contiguous memory locations,
similar to arrays. The elements can be accessed not only using iterators but also
using the subscript operator [ ] in the same way as with arrays.
As we will see, insertions and deletions can actually be made anywhere in the
container but this process is less efficient than methods provided by the other
containers, list and deque.
Vectors are most commonly used when the data has to be sorted and accessible
via a subscript operator, m y V e c t o r [ 1 0 ] ;
Vectors support r a n d o m a c c e s s i t e r a t o r s and this means all the operations
shown in Table 14 can be applied to the class objects.
This also means that all STL algorithms will operate on a vector object. This is
because random access iterators combine their own functionality together with
the functionality of all the other iterator categories.
Task 1 Exercise 73
Open V e c s A n d I t s in Open V e c s A n d I t s and examine the code.
the V e c t o r s a n d Only the parts that relate to vectors, iterators and
I t e r a t o r s folder and
algorithms are covered.
examine the code to
establish how to read Have a look at the code shown in Figure 183. The
and write files. code shows the function prototype for template
function O u t P u t V e c t o r E l e m e n t s .
Using a function template allows constant references
to vectors holding any kind of object to be passed to
the function and output to screen. In the example we
pass vectors of integers and doubles.
Note the vector reference being passed is a c o n s t a n t
so any iterators we use must also be constant.
Figure 183
Exercise 74
In the statements d o u b s . p u s h _ b a c k ( a + 1 . 3 ) ; and
i n t s . p u s h _ b a c k ( a + 1 ) ; we use the vector member
function p u s h _ b a c k ( ) .
p u s h _ b a c k is available to all sequence containers
and pushes additional data to the back of the vector,
either into elements that are empty or by allocating
additional memory and increasing the size of the
vector.
Exercise 75
The statement O u t P u t V e c t o r E l e m e n t s ( i n t s ) ;
passes the vector i n t s to the template function.
Exercise 76
Examine the code shown in Figure 184. The
statement is used to create a constant reverse iterator
called c o n R e v I t .
Notice that c o n s t _ r e v e r s e _ i t e r a t o r is a f o r w a r d
o n l y iterator, see Table 14.
This means, as the names suggest the iterator can only
move forwards through the container.
Importantly, f o r w a r d i t e r a t o r s do not support the <
“less than" operator.
Figure 184
Exercise 77
Figure 185 shows the creation of another constant
reverse iterator (a forward iterator) being initialised
with the iterator returned from r e n d ( ) .
The significance of this is explained in the next step.
Figure 185
Exercise 78
In Figure 186 the f o r loop condition is testing to see if
the iterator c o n R e v I T is not equal to iterator
conTempIT.
It would seem intuitive to write this conditional
statement as c o n R e v I T < c o n R e v I T . r e n d ( )
However, c o n R e v I T is a forward iterator and does
not support the < operator so we assigned the iterator
r e n d ( ) to c o n T e m p I T (Figure 185) and use the two
iterators as a comparison condition using operator ! =
see Figure 186 .
Figure 186
Exercise 79
The statement shown in Figure 187 creates a
c o n s t a n t iterator that can read a const element in a
vector.
Figure 187
Exercise 80
In Figure 188 the f o r loop condition is testing to see if
the iterator c o n I T is less than the iterator returned by
inValue.end().
N o t e that we can use the test condition operator <
(less than), as c o n I T is a random- a c c e s s iterator.
Figure 188
Task 1
Modify the program to
read from file i n t s . t x t
all the values into a
vector of integers. Show
the vector before and
after sorting.
Read in the values from
d o u b s . t x t . Use the
template function to
show the vector before
and after sorting.
The output should be
similar to Figure 189 Figure 189
Task 1 Exercise 82
Create a new project. The max and min values can be established using the
STL algorithms, m a x _ e l e m e n t and m i n _ e l e m e n t .
Read the data from the
file d o u b s . t x t into a m a x _ e l e m e n t returns an iterator pointing to the
vector. largest element in a range and m i n _ e l e m e n t returns
an iterator pointing to the smallest element in a range.
Establish the max,
minimum and mean The format for m i n _ e l e m e n t is shown in Figure 190.
values in the vector. You will also need to create a vector iterator to assign
the returned iterator to. In this example it’s called
myIterator,
m y I t e r a t o r can be used with the dereference
operator to output the minimum and maximum
values, see Figure 191.
Note, remember to include the header < a l g o r i t h m > .
Figure 190
Figure 191
Exercise 83
Create a template function that can take any kind of
vector and the code necessary to calculate the m e d i a n
of a range.
If a vector has an odd number of elements the median
is middle vector element, otherwise the median is
(sum of the middle two elements of the vector / 2).
The completed program when run should look similar
to Figure 192.
Exercise 84
Figure 192
Figure 193
Exercise 87
In Figure 194 the p u s h _ b a c k member function is
used to add values to the end of the list.
L i s t containers also have member functions
p u s h _ f r o n t and p o p _ f r o n t allowing insertion and
removal of elements from the front of the list.
Figure 194
Exercise 88
In Figure 195 a reference is assigned to iterator i t 1 of
the first element in the list d o u b . b e g i n ( ) .
i n s e r t ( ) member function adds an element b e f o r e
the element pointed at by iterator i t 1 .
In this example we are adding 6 9 . 6 9 at the beginning
of the list.
Note: after i n s e r t ( ) iterator i t 1 is still pointing at the
same value in the list that was identified as
d o u b . b e g i n ( ) , i.e. now the second element.
N o t e : this version of the i n s e r t ( ) member function
returns an iterator pointing to the newly added
element. However, as shown here, it does not have to
be used.
Figure 195
Exercise 89
In Figure 196 the s o r t ( ) member function is used to
sort the elements in the container from lower to
higher.
Sorting is performed by comparing the elements in
the container in pairs using a sorting algorithm.
The comparisons are performed using the < operator
between the element.
Figure 196
Exercise 90
In Figure 197 the s o r t ( ) member function is used sort
the list d o u b s ( ) .
The merge member function is then used to merge
d o u b s with list d o u b , the merge is to list d o u b .
N o t e that this will empty the second list d o u b s .
Figure 197
Exercise 91
In Figure 198 we want to copy the contents of d o u b ( )
list to the now empty list d o u b s ( ) . To do this we use
the c o p y ( ) algorithm.
The c o p y algorithm uses i n p u t i t e r a t o r and o u t p u t
i t e r a t o r that are supported by l i s t containers
N o t e : before using the c o p y algorithm the list
d o u b s ( ) has to be resized using list member function
r e s i z e ( ) to match the size and number of elements
that will copied into it.
Figure 198
Exercise 92
In Figure 199 the u n i q u e member function removes
all but the first element from every consecutive group
of equal elements in the list container.
Elements are only removed from the list if they are
equal to the element immediately preceding it.
Therefore a list should be sorted first before using this
member function.
Figure 199
Exercise 93
Figure 200 shows how to exchange the content of the
list d o u b with the content of d o u b s .
Obviously both lists must contain elements of the
same type but list s i z e s may differ.
After the call to the member function the elements in
d o u b container are those which were in d o u b s , and
the elements of d o u b s are those which were in d o u b .
N o t e that an a l g o r i t h m exists with the same name
s w a p , which has the same behaviour.
Figure 200
Exercise 94
In Figure 201 iterator i t 1 is positioned at the start of
the list using function b e g i n ( ) .
STL class iterator a d v a n c e ( ) advances the iterator
i t 1 , twice to the third element of the d o u b list.
Iterator i t 1 will be used with the s p l i c e ( ) member
shown in Figure 202.
Figure 201
Exercise 95
Figure 202 member function s p l i c e ( ) is used to move
elements from list to list.
Elements are moved from m y L i s t into the list
container d o u b at the specified position i t 1 .
N o t e : iterator i t 1 has already been moved to the third
element position.
The element at location i t 2 in m y L i s t , “10” is moved
from m y L i s t into list d o u b .
m y L i s t has one element less and d o u b has one
element added at position i t 1 .
Figure 202
Exercise 96
Figure 203 shows how to use the s p l i c e member
function with a different template. This function
template needs four parameters.
P a r a m e t e r 1 is the position in the container where
the elements of m y L i s t are inserted; d o u b . b e g i n ( ) .
P a r a m e t e r 2 is the list object m y L i s t containing the
same type of objects as d o u b container.
P a r a m e t e r s 3 & 4 are iterators specifying a range of
elements in m y L i s t . The elements in this range are
moved to d o u b . b e g i n ( ) .
Notice that the range includes all the elements
between i t 1 and m y L i s t . e n d ( ) the element pointed
by i t 1 but not the one pointed by m y L i s t . e n d ( ) as
this points past the last element in the list.
Figure 203
Task 1 Exercise 97
Create a new project, call Create a l i s t and l i s t i t e r a t o r .
it L i s t F i n d A n d Load the file L i s t N u m b e r s . t x t to the l i s t .
Erase
Exercise 98
Use the f i n d ( ) STL algorithm (there is no member
function) to return an iterator to the position in the
list of a known number.
it = find (myList.begin(), myList.end(), anInt);
Exercise 99
Add a number of your choice together with the
returned iterator from f i n d to the i n s e r t member
function. The statement should be similar to
myList.insert (it,value);
Exercise 100
Insert the elements from a vector into the list from the
beginning of the list. See Figure 204 for a possible
way to achieve this.
Figure 204
Exercise 101
Find the three digit number in the list and erase it.
The program when completed and run should look
similar to Figure 205
Figure 205
Both v e c t o r s and d e q u e s provide a very similar interface and can be used for
similar purposes, but internally both work in quite different ways.
Figure 206
Exercise 104
Figure 207 shows how to use the s o r t ( ) algorithm,
elements are sorted into ascending order.
Class deque does not have a member function sort,
but we can make use of the s o r t ( ) alogorithm.
m y D e q u e . b e g i n ( ) and m y D e q u e . e n d ( ) return
random-access iterators to the initial and final
positions of the sequence to be sorted.
Figure 207
Exercise 105
Figure 208 shows how to use the i n s e r t ( ) member
function with d e q u e .
The d e q u e container is extended by inserting new
elements before the element at the specified position.
This increases the container size by the amount of
elements inserted.
Remember that deques are designed to be efficient at
performing insertions (and removals) from either end
of the sequence.
Insertions and deletions on other positions are less
efficient. If you need to do this it’s best to use a l i s t
container.
Figure 208
Exercise 106
Figure 209 shows the deletion of a deque element
other than at the end of the container.
m y D e q u e . b e g i n ( ) + 5 returns an iterator to the
element to be erased, in the middle of the deque.
Remember that if you intend to insert or erase
elements from the middle of your container it is more
efficient to use a l i s t .
Figure 209
Exercise 107
Examine the code in Figure 210. In this example we
are using the i n s e r t function with a different number
of parameters.
The parameters here indicate where in the d e q u e the
elements will be inserted (i t 1 ) and the range of
elements to be inserted m y V e c . b e g i n ( ) to
myVec.end().
N o t e that the element pointed to by m y V e c . e n d ( ) is
not copied.
Figure 210
Task 1
Modify the program in
D e q u e A n d I t s . d e v so
only the first two
elements in m y V e c are
copied to the deque.
Figure 211
Exercise 110
In Figure 212 the t y p e d e f keyword creates an alias
called m u l t S e t for a m u l t i s e t container data type.
T h e e f f e c t o f t h i s s t a t e m e n t i s t o s o r t the
m u l t i s e t from l o w e s t to h i g h e s t .
Figure 212
Figure 213
It is useful to define types when it is possible that the
d a t a t y p e will change in later versions of the
program, or if a type you want to use has a name that
is too long or confusing.
Exercise 111
The statement shown in Figure 212 uses the
l e s s < i n t > function object for less-than inequality
comparison.
l e s s has its operator ( ) member defined such that it
returns t r u e if its f i r s t argument compares lower
than the second one using operator < , and f a l s e
otherwise.
The effect of "l e s s " is to s o r t the m u l t i s e t from
l o w e s t to h i g h e s t .
To sort from highest to lowest use "g r e a t e r " function
object.
Exercise 112
Figure 214 shows the c o u n t ( ) member function being
used to search the container for an element with a key
of 1 5 .
The function returns the number of times the element
appears in container i n t M u l t i s e t .
Figure 214
Exercise 113
Figure 215 shows the creation of constant iterator
called r e s u l t .
The scope resolution operator : : is used to enable the
name of the member that follows the operator
(c o n s t _ i t e r a t o r ) to be looked up in the scope of the
class with the name that appears before the operator.
The correct type of iterator is then created, in this case
for multiset, b i d i r e c t i o n a l .
Figure 215
Exercise 114
Figure 216 shows the use of the f i n d ( ) member
function which returns a bidirectional iterator.
The function is used to search the container for an
element with a value of 1 5 and return the iterator to it
if found.
If the value is not found an iterator to
m u l t i s e t : : e n d ( ) is returned. The e n d ( ) iterator
points to the element past the end of the container
and it is possible to test for this.
Figure 216
Exercise 115
The code shown in Figure 217 tests to see if the
returned iterator points to the end of the multiset.
In Figure 217 the returned iterator type is used to
determine the output.
Figure 217
Exercise 116
Figure 218 shows the use of i n s e r t member function
to extend the container by adding all of array a
elements.
a and a + S I Z E are iterators specifying a range of
elements to be inserted into the multiset. From the
beginning to the end of the array a .
Figure 218
Exercise 117
In Figure 219 l o w e r _ b o u n d returns an iterator
pointing to the first element in the container which
does not compare less than 2 4 (using the container's
comparison object, defined in t y p e d e f , in this case
l e s s ).
A pointer is returned to a value that is either equal to
or greater than the key value, d e r e f e r e n c e d here.
Figure 219
Exercise 118
Figure 220 shows u p p e r _ b o u n d member function
which returns an iterator pointing to the first element
in the container which compares greater than the k e y ,
2 4 (using the container's comparison object, l e s s ).
Unlike l o w e r _ b o u n d , this member function does not
return an iterator to the element if it compares equal
to 24, but only if it compares strictly g r e a t e r .
If the iterator is passed the container last element its
equal to i n t M u l t i s e t . e n d ( ) so we test for this, if this
is true the key cannot in multiset so output
accordingly.
Figure 220
Exercise 119
Figure 221 shows the use of the p a i r s utility
components. p represents a pair of c o n s t _ i t e r a t o r s ,
in this case m u l t S e t c o n s t _ i t e r a t o r s .
The p a i r class couples together a pair of values, which
may be of different types. The individual values are
accessed through the public members f i r s t and
second.
Figure 221
Exercise 120
Figure 222 shows the member function e q u a l _ r a n g e
returning a pair of iterators, p . f i r s t and p . s e c o n d .
Member p . f i r s t is an iterator to the lower bound of
the range with the same value as would be returned by
lower_bound(key).
p . s e c o n d is an iterator to the upper bound of the
range with the same value as would be returned by
upper_bound(key).
So it’s another way to get l o w e r _ b o u n d and
u p p e r _ b o u n d values.
Figure 222
Exercise 121
The values pointed at by the returned iterators are
output using the d e r e f e r e n c e operator and the
members as shown in Figure 223.
Figure 223
Figure 225
Exercise 125
Figure 226 shows the creation of an instance of
t y p e d e f m u l t m a p called c C a r d N o .
Figure 226
Exercise 126
In Figure 227 two v a l u e _ t y p e objects are inserted in
c C a r d N o multimap. The values entered are integers
and doubles for the k e y & v a l u e of the first two
elements.
v a l u e _ t y p e is a synonym for t y p e as defined in the
t y p e d e f for multimap at the start of the program, in
this case the k e y is type i n t and the v a l u e type
double.
Figure 227
Exercise 127
Figure 228 shows the use of a c o n s t _ i t e r a t o r named
i t e r to run through c C a r d N o multimap using pointer
notation to access members f i r s t and s e c o n d .
The iterator defined by m u l t i m a p points to objects of
v a l u e _ t y p e which are of type p a i r <c o n s t K e y ,
Type>.
The value of the K e y is available through the first
member pair and the value of T y p e of the mapped
element is available through the second member of
the pair.
To dereference an iterator i t e r pointing to an element
in a m u l t i m a p we use the arrow - > operator.
To access the value of the key for the element, use i t e r
- > f i r s t which is equivalent to ( * i t e r ) . f i r s t .
To access the value of the mapped data for the
element use i t e r - > s e c o n d which is equivalent to
(*Iter).second.
Figure 228
Figure 230
Exercise 129
Use the m u l t i m a p c o u n t ( ) member function in a f o r
loop to total the number of transactions for each of
the first twenty account holders, see Figure 231.
Figure 231
Exercise 130
Still inside the f o r loop add code similar to Figure
232.
The function e q u a l _ r a n g e returns a p a i r , where its
member p a i r : : f i r s t is an iterator to the lower bound
of the range (ex the first of many 1's).
p a i r : : s e c o n d is an iterator to the upper bound of the
range (ex the last of many 1's).
i n d t o t a l is the sum of the mapped v a l u e for each
transaction for each account.
Figure 232
Task 1
Modify the program to
send the total
transactions for each of
the first 20 customers
(ID’s 1-20) to file.
Save the file as
clientsDebt.txt.
The file should look the
same as Figure 233
Figure 233
Table 18
24 Appendix
24.1. Arithmetical Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
The a s s i g n m e n t o p e r a t o r in C++ is = .
The format is v a r i a b l e = e x p r e s s i o n ; this can be read as, assign to the
v a r i a b l e the value of the e x p r e s s i o n .
An example to calculate the number of pence in a value in pounds would be:
pence = pounds * 100;
N o t e : it is easy to confuse the assignment operator = with the equals notation
used in mathematics. The equals notation in C++ is = = .
Incrementing a variable.
To add 2 to a variable t o t a l :
total = total + 2; or t o t a l + = 2 ;
To subtract 2 from t o t a l :
total = total - 2; or t o t a l - = 2 ;
To multiply t o t a l by 2 :
total = total * 2; or t o t a l * = 2 ;
Relational operators
> > a>b a is greater than b
< < a<b a is less than b
>= a >= b a is greater than or equal to b
<= a <= b a is less than or equal to b
Equality operators
= == a == b a is equal to b
!= a != b a is not equal to b
Table 19
Escape Description
Sequence
\n Newline. Position the screen cursor at the beginning of
the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
\r Carriage return. Position the cursor at the beginning of
the current line.
\a Alert. Sound the system bell.
\\ Backslash, used to print a backslash.
\’ Single quote. Use to print a single quote character.
\” Double quote. Used to print a double quote character
24.10. Scope
The portion of a program where an identifier can be used is known as its scope.
An identifier declared outside any function or class has f i l e s c o p e . This type of
identifier is “known” by all functions. Global variables and function prototypes
all have file scope.
Identifiers declared inside a block of code have b l o c k s c o p e . This type of scope
begins at the identifiers declaration and ends at the termination right brace (} ) of
the block in which the identifier is declared.
Any block can contain local variable declarations. If blocks are nested it is
possible to declare variables with the same name in each nested block. The
variable in the outer block is hidden while the inner block is being executed.
24.12. Constants
Data that will not change during the execution of a program should be stored in a
constant container rather than a variable. If the program attempts to change the
value stored in a constant the compiler will report an error and compilation will
fail.
Constant can be created for any data type by prefixing the declaration with c o n s t
keyword followed by a space. Note: Constants must always be initialised at
declaration.
The following declaration declares a constant for the speed of sound at sea level
m/s.
The string class defines many m e m b e r f u n c t i o n s . A few of the basic ones are
described below:
Non-member functions
string name;
Copies the string a2 into the char array a1. The value of
a1 is returned.
E x a m p l e : strcpy(a1, a2); copy the contents of array a2 into array a1.
N o t e : the programmer must ensure the first array (a1) is large enough to store the string in
a2.
char *strncpy(char *a1, const char *a2, size_t n);
Note: the above function prototypes are located in the header file < c s t r i n g > .
Decim
al Octal Hexadecimal Binary Value
0 0 0 0 NUL (Null char.)
1 1 1 1 SOH (Start of Header)
2 2 2 10 STX (Start of Text)
3 3 3 11 ETX (End of Text)
4 4 4 100 EOT (End of Transmission)
5 5 5 101 ENQ (Enquiry)
6 6 6 110 ACK (Acknowledgment)
7 7 7 111 BEL (Bell)
8 10 8 1000 BS (Backspace)
9 11 9 1001 HT (Horizontal Tab)
10 12 00A 1010 LF (Line Feed)
11 13 00B 1011 VT (Vertical Tab)
12 14 00C 1100 FF (Form Feed)
13 15 00D 1101 CR (Carriage Return)
14 16 00E 1110 SO (Shift Out)
15 17 00F 1111 SI (Shift In)
16 20 10 10000 DLE (Data Link Escape)
17 21 11 10001 DC1 (X ON) (Device Control 1)
18 22 12 10010 DC2 (Device Control 2)
19 23 13 10011 DC3 (X OFF)(Device Control 3)
20 24 14 10100 DC4 (Device Control 4)
21 25 15 10101 NAK (Negative Acknowledgement)
22 26 16 10110 SYN (Synchronous Idle)
23 27 17 10111 ETB (End of Trans. Block)
24 30 18 11000 CAN (Cancel)
25 31 19 11001 EM (End of Medium)
26 32 01A 11010 SUB (Substitute)
27 33 01B 11011 ESC (Escape)
28 34 01C 11100 FS (File Separator)
29 35 01D 11101 GS (Group Separator)
(Request to Send)(Record
30 36 01E 11110 RS Separator)
31 37 01F 11111 US (Unit Separator)
32 40 20 100000 SP (Space)
Decim
al Octal Hexadecimal Binary Value
33 41 21 100001 ! (exclamation mark)
34 42 22 100010 " (double quote)
35 43 23 100011 # (number sign)
36 44 24 100100 $ (dollar sign)
37 45 25 100101 % (percent)
38 46 26 100110 & (ampersand)
39 47 27 100111 ' (single quote)
40 50 28 101000 ( (left/opening parenthesis)
41 51 29 101001 ) (right/closing parenthesis)
42 52 02A 101010 * (asterisk)
43 53 02B 101011 + (plus)
44 54 02C 101100 , (comma)
45 55 02D 101101 - (minus or dash)
46 56 02E 101110 . (dot)
47 57 02F 101111 / (forward slash)
48 60 30 110000 0
49 61 31 110001 1
50 62 32 110010 2
51 63 33 110011 3
52 64 34 110100 4
53 65 35 110101 5
54 66 36 110110 6
55 67 37 110111 7
56 70 38 111000 8
57 71 39 111001 9
58 72 03A 111010 : (colon)
59 73 03B 111011 ; (semi-colon)
60 74 03C 111100 < (less than)
61 75 03D 111101 = (equal sign)
62 76 03E 111110 > (greater than)
63 77 03F 111111 ? (question mark)
64 100 40 1000000 @ (AT symbol)
65 101 41 1000001 A
66 102 42 1000010 B
67 103 43 1000011 C
68 104 44 1000100 D
69 105 45 1000101 E
70 106 46 1000110 F
71 107 47 1000111 G
72 110 48 1001000 H
73 111 49 1001001 I
74 112 04A 1001010 J
75 113 04B 1001011 K
76 114 04C 1001100 L
Decim
al Octal Hexadecimal Binary Value
77 115 04D 1001101 M
78 116 04E 1001110 N
79 117 04F 1001111 O
80 120 50 1010000 P
81 121 51 1010001 Q
82 122 52 1010010 R
83 123 53 1010011 S
84 124 54 1010100 T
85 125 55 1010101 U
86 126 56 1010110 V
87 127 57 1010111 W
88 130 58 1011000 X
89 131 59 1011001 Y
90 132 05A 1011010 Z
91 133 05B 1011011 [ (left/opening bracket)
92 134 05C 1011100 \ (back slash)
93 135 05D 1011101 ] (right/closing bracket)
94 136 05E 1011110 ^ (caret/cirumflex)
95 137 05F 1011111 _ (underscore)
96 140 60 1100000 `
97 141 61 1100001 a
98 142 62 1100010 b
99 143 63 1100011 c
100 144 64 1100100 d
101 145 65 1100101 e
102 146 66 1100110 f
103 147 67 1100111 g
104 150 68 1101000 h
105 151 69 1101001 i
106 152 06A 1101010 j
107 153 06B 1101011 k
108 154 06C 1101100 l
109 155 06D 1101101 m
110 156 06E 1101110 n
111 157 06F 1101111 o
112 160 70 1110000 p
113 161 71 1110001 q
114 162 72 1110010 r
115 163 73 1110011 s
116 164 74 1110100 t
117 165 75 1110101 u
118 166 76 1110110 v
119 167 77 1110111 w
120 170 78 1111000 x
Decim
al Octal Hexadecimal Binary Value
121 171 79 1111001 y
122 172 07A 1111010 z
123 173 07B 1111011 { (left/opening brace)
124 174 07C 1111100 | (vertical bar)
125 175 07D 1111101 } (right/closing brace)
126 176 07E 1111110 ~ (tilde)
127 177 07F 1111111 DEL (delete)