Professional Documents
Culture Documents
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 ke t hi s .
Drop-down menu options are indicated by the name of the option
enclosed in square brackets, for example Fi l e | P rin t . To select the
option P rin t from the Fi le menu: click with the mouse button on the
Fi l e menu name; move the cursor to P ri nt ; when P rin t is highlighted,
click the mouse button again.
A button to be clicked will look l i ke t hi s .
The names of software packages are identified like this, and the names of
files to be used li ke th 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 so u rce 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 bj e ct 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 ri ve and double click on the program
de vcpp -4 .9 . 9. 2 _se tu p. e xe , see Figure 1.
Figure 1
Step 2
Figure 2
Step 3
Figure 3
Step 4
Click the I Ag ree button when you get to the License
Agreement window, see Figure 4.
Figure 4
Step 5
Click on Ne xt when you see the Choose Components
window, see Figure 5.
Figure 5
Step 6
Click the I n st 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 Fi n i sh , see Figure
8.
Figure 8
Step 9
At the Beta version Notice click OK , see Figure 9
Figure 9
Step 10
When you see the De v-C++ f i rst t i me co nf i gu ra t io n
window (Figure 10) click the
> Ne xt button.
Figure 10
Step 11
Make sure Y e s, I wa nt to use th i s f ea t u re is
selected then select the > Ne xt button to select
additional features, see Figure 11.
Figure 11
Step 12
To create the code completion cache click the
> Ne xt 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 OK .
Figure 13
Step 14
Close the Ti p o f t he da y window by clicking the
Clo se 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 "la un ch pa 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 Fi l e => I mpo rt
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 NAL
window or select St a rt | A ll P rog ra ms | Bl oo d sh e d
De v-C++ | De v-C++ .
Figure 24
Select Con so le Ap pl i ca ti o n
Add a project the name of We l co me
Select the C++ P roj e ct radio button
Click OK
Save the project to the \ as We l co me .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 He l lo 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
# in cl ud e <i o st re a m>
Notifying the pre-processor to include in the program the contents of the header
file i o st re a m before compilation. This file must be included for any program that
outputs data to the screen or inputs data from the keyboard
u sin g n a me sp a ce std ;
Using the namespace st d tells the compiler to treat the names (me mb e rs of the
namespace st d ) in the sta nd a rd l i b ra ry as though we had defined them in the
current program. The members we will be using throughout our programs are :
ci n - is the "standard input stream object" of the namespace std and we must
include the header file <i o st rea m> in order to use them (you will be using this in
the next exercise). The cin object enables a program to input data from the
keyboard or other device.
cou t - is the “standard output stream object” of the namespace std (you will be
using this in the next exercise). The cou t object enables a program to output data
to the screen or other devices
e nd l - is a stream manipulator that writes a new line to output. en dl stands for
e nd of li ne and is pronounced “endell”.
st ri ng - allows us to use the st rin g cl a ss (more on classes later) as an alternative
to using C style character arrays.
"na me sp a ce s " are an advanced C++ feature. Dev-C++ adds the above statement
and for now we should accept this in the program.
In the programs we will be creating in this session we will not be using the
arguments a rg c and * a rg v[] and the statement in t ma i n (in t a rg c, ch a r
*a rg v[ ] ); could be replaced with i nt ma in () .
Task 1 Step 1
Modify the program Add the following statements immediately above the
statement re t u rn E XI T_S UCCE S S ;
int anum = 0;
cin >>anum;
Step 2
Save the file as ma i n. cp p
Task 2 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 3 Step 1
Run the program Run the project and select the box in Eclipse labelled
“Con so le ” as in Figure 31.
Enter a number at the prompt and press En te 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 in t eg 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 Ca st 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 xf o rd ” or “S t. A nd re ws ”. 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 na me . You could create a second string and get the user to
enter B la ck 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 me until the <ENTER> key is pressed. The ge t li 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
st at i c_ca st notation as shown here:
int anInt;
anInt = static_cast<int>(doubResult); where d ou b Re su 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 bI nt is an integer.
Task 3
Modify your program in
Ta sk 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 AS CI I
integer values of each
character.
Task 4
Create another project
called Ad d re ss .
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 Ca l cA rea .
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. 14 15 9 2
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 ea rch St ri 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. En cap su la t io 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 de cla re d with a p ro to t yp e early in the program. A function
prototype consists of the re t u rn t yp e , a fu n ct i on n a me and a pa ra me te r l i s t
indicating the data the function will receive. The function prototype is also called
the function de cla ra t io n .
The function d ef i ni t i on consists of the prototype and a function body, which is a
block of code enclosed in parenthesis.
Using a p ro t ot yp 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 ef i ni t i on creates the actual function in memory.
Arguments can be passed to functions in two ways. Pa ss-b y-va lu 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 pa ssed -b y-re f e ren ce . 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 po in t e rs can be used to p ass- by- ref e ren ce .
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
Cha rNu mS t ri ng Fu n c
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 ro t ot yp e s in this program. Creating
prototypes allows the compiler to perform t ype
checking on the arguments to ensure the input data is
the correct type before processing it.
Cal l i ng fu n cti o n s:
readChar(); This is a function call to the
rea d Cha 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;
Fu n ct io n De f in i t io n s:
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 en g th () . This is returned to
the calling statement.
void readDouble()
{
static int aNum = 1;
aNum +=1;
}
Not e here the use of the keyword sta t i c . This has
defined the memory location a Nu 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 st at 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
ad de d to the variable a Nu m .
Task 2
Remove the key word
sta t i c from the
declaration static in t
a Nu m = 1 ;
this is in the vo i d
rea d Dou b le () function.
Compile and run the
program and see how the
program responds.
Task 1 Step 1
Open the project Eve n Read two integers in to ma 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 in t Ca l cs() 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 ma i n (). Pass the
two doubles and the value of one integer to the second
function, the prototype is in t Ca l cs(d ou b le , do ub le ,
in t );
Within function Ca l cs() write statements to produce
the output as shown in Figure 36.
Most of the code already exists within ma 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 ma in (), 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 ma i n () to
the function and the
results of the changes
displayed from within
the function.
Task 3
Create a new project, call
it Chu rch He ig h t .
Write a program that
will calculate the height
of a building given the
following information.
You are 27 0 metres
away from a church. The
angle from your feet to
the top of the church is
16 degrees, see Figure 37
and Figure 38.
The height of the Figure 37
building can be
calculated using the
formula:
ta n (an g le ) = l en gt h of
op po si te sid e / l en g th
of th e a dj a ce n t si de .
rad i an s =
de g re e s*∏/ 18 0 .
The program should
contain at least two
functions to calculate the
height of the building.
You will need to convert
the angle to radians Figure 38
before using the cmat h
function ta n (x) . See
Appendix 24.15 for more
information on cma t h
functions.
Remember to include
the header file <cma t h >
in your program.
Task 4
Create a new project, call
it Met re s .
Write a function named
FIt o Me te rs 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 Se con d s .
Two identical
experiments have been
conducted and the time
difference between the
two (in seconds) is
critical.
Write a function
(HMS e con 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 ma in () . The arguments were
passed by their va l ue .
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 (ma in () 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 va l ue -arguments cannot change the variable
passed from ma in () because any changes only apply to local copies in the
function, not the actual caller's variables.
Passing variables to functions by re f e re n ce 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 con st and pass them by reference.
The format of a function prototype when using call by reference is:
re t u rn - da ta - typ e f un ct io n -n a me (re fe re n ce p a ra me te r). To indicate a
reference parameter, an ampersand (& ) is written in the function prototype and
header after the parameter t yp e name
The statement void squared(int &); has no return data type (vo id ), it’s name
is sq u a re d and it accepts a ref e re n ce pa ra met e r (& ) of type in t (integer).
Task 1 Step 1
In ecl i p se , o pe n t he Compile and run the program. The output should be
p ro j e ct Fu n ct io n Ref the same as shown in Figure 39.
Figure 39
Examine the function prototype:
vo i d sq ua re d (in t & );
This shows the function sq u a re d accepts a ref e re n ce
pa ra me te r of type i nt . The reference parameter is the
memory ad d re ss 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 ma in () . A reference
to this address is passed to the function with the
function call sq u a re d (a );
Step 2
Examine the function vo id sq u a red (i n t & x)
x refers to the a dd re ss 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, ma in () in this example.
Task 2
Create another project
call it Fu n cRe f Ma rks .
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 ma i n ()
function. The output
should be similar to that
shown in Figure 40.
Task 3
Open the file
Fu n cCon st Re 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 tt ri b ut 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 be ha vi ou rs 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, ob je ct . me mbe rf u n ct i on na me (). An example is
st ud en t 1. g et Na me () . The object is stu de n t1 and the member function is
g et Na me () .
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 ma 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 St ud e nt . Name the
new source file
St ud e nt UG . cpp .
From the directory
where you unpacked the
source materials, open
the file called
St ud e nt UG . t xt . Copy
the C++ program.
Replace the default C++
template file
(S tu de n t UG . cp p ) with
the file copied from Figure 42
St ud e nt UG . t xt .
The program should look
like Figure 42.
Compile and run the
program.
Before you can create the object myNa me 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.
In order for the function d i sp l a yNa me () to recognise the parameter being passed
the function declaration is changed to include the parameter (n a me ) and type
(st rin g ) as shown in Figure 43.
Figure 43
The statement cout <<"Hello " << name << endl; provides the output.
Task 1
Modify the program you
created in the previous
exercise S tu de n t UG . cp 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 ob je ct s
(instances) of the class.
Figure 45
When data members are declared as p ri vat e the data is hidden. This is called
e nca p su l at i on 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
me mb e r fu n ct i on to set the data member to a value and create a second me mb e r
f un ct io n to output the value held there.
Data members can also be declared p ub l i c . A data member that is declared
p ub l i c can be accessed from any (non-member) function.
A p ro t e ct 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
St ud e nt G et S et . Create a
new source file call it
St ud e nt Co u rse. cp p .
Fro m th e d i re ct o ry whe re
yo u un pa cke d th e sou rce
mat e ri a l s, op en th e f i le
ca l l ed Ge t Se t .t xt .
Copy the C++ program.
Replace the default C++ Figure 46
template file
(S tu de n t Cou rse . cp p ) with
the file copied from
Ge t Se t .t xt .
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 ret u rn Na me ()
shown in Figure 47. This
function produces the
output but what does
ge t Na me () do?
Figure 47
Task 3
Modify the St ud e nt Co u rse
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.
You will need to create
Figure 48
additional da ta me mbe rs
and me mbe r f un ct io n s to
achieve this.
The output should be
similar to Figure 48.
7.4. Constructors
When you create objects from the S tu de n t Cou rse 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 cou rse Na me data member (it is possible to initialise some or all of
the data members) when each object is created.
A co n st ru ct o r is a special kind of function that must have the same name as the
class. Constructors are normally defined as p ub 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 ef au l t co n st ru ct 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 ve rl o ad 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
Con st ru cto r . Create a new
source file call it
Con st ru cto r. cpp .
Fro m th e d i re ct o ry whe re
yo u un pa cke d th e sou rce
mat e ri a l s, op en th e f i le
ca l l ed co n st ru ct o r. t xt .
Copy the C++ program.
Replace the default C++ Figure 50
template file
Con st ru cto r. cpp with the
file copied from
co n st ru ct o r. t xt .
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
se t Co u rse Na me (n a me );
do?
Figure 51
Task 3
Create a third constructor
that will take arguments of
ye a rs and en ro l Dat e .
Add a third object, call it
stu de n t3 .
Write a statement that will
output the results of a call
to this additional
constructor.
Task 4
Each student has an I D
nu mbe r and a sup e rvi so r .
Modify the program to
allow student I D’s and the
na me 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
su p e rvi so r n a me s .
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:
Staff (int staffid = 0, double sal = 0.0); /*constructor*/
double getSal()
{return staffsal;
}
}; /*end of class*/
Task 1 Step 1
Open an existing project. I n e cli p se, op en th e p ro je ct He ad e r
Create a header file and Add a new Source file to the project, Fi le | Ne w |
include reference to this in S ou rce Fil e
the source code file. Save and name the file O xS t ud en t s.h in the same
When ma in () is called the folder as He ad e r .
class definition in the
header file is used to create
objects of the class defined
in the header file. Step 2
Cut the class definition code from He ad e r. cpp file
and paste it into the O xSt u de 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 clu de <i o st re a m>, # in cl ud e
<st ri n g > and usi ng na me spa ce st d; to the top of
the header file.
Step 3
Compile the program
You should get a compilation error at line
O xSt u de n t s myNa me ;
This is because ma i n () does not know about the
header file containing the class information.
Step 4
Add the statement # in cl ud e "O xS t ud en t s. h "
beneath the other #i n clu de directives in
He ad e r. cpp file.
Compile and run the program
The statement #i n clu de "O xS tu de n t s. h " instructs
the C++ pre-processor to replace the directive with
a copy of the contents of O xSt u de n t s. h before the
program is compiled.
With the O xSt u de 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 ma i n ().
No te : 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
No te : 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 2
Create another project call
it Cou n t ry . Modify the
ma in () source code to use
the class in the header file
#i n clu de "O xS tu de n t s. h " .
Not e : the O xstu d en t s.h
file will need to be copied to
the Co un t ry project folder. Figure 52
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 3
Open the project
Con st ru cto r you created in
Exercise 12.
Create a new header file
that includes the class
definition, save this as
co n st ru ct o r. 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 4
OPTIONAL
Task 1 Step 1
In ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct If . There is
one . cp p file and one .h Run the program. The output should be the same as
header file. Figure 54.
Figure 54
Step 2
Examine the vo id ge t G ra d e s() member function in
the S tu de n t Ma rksIn t e rfa ce .h file.
The if single selection statement performs only one
action when the condition tested (E xa m1 >= 9 0 ) i s
t ru e .
if (E xa m1 >= 90 )
cou t << "th e Exa m1 g rad e is 'A '" <<e n dl ;
Figure 55
The appropriate grade is selected and user prompted
of the result from within ge tG ra d e s() member
function.
Task 2
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 Cou rse Na me .
Output the results to Figure 56
screen. They should
look similar to Figure 56.
Task 1
In ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct If S wi t ch . Run the program. The output should be the same as
There are two files, one Figure 57.
. cp p files and one . h
header file.
Figure 57
Task 2 Step 1
To see how the swi t ch Examine the vo id ge t G ra d e s() member function in
statement gets its the S tu de n t Ma rksIn t e rfa ce .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 swi t ch statement. exercise. The statement co u nt G ra de s (‘A ’) is new. It
is calling the function co u nt G ra de s and passing a
character parameter ‘A ’ as the student achieved >= 9 0
ma rks .
Figure 58
Step 2
Exam the code in cou n t G ra d e s member function.
See Figure 59
Figure 59
Task 3 Step 1
Exam how the count of Examine the member function o ut Pu t G rad e s()
grades is output. shown in Figure 60
Figure 60
This member function outputs the object member
variables a Co un t . .. f Co un t . The statement
stu de n t1 . ou t Pu t G rad e s(); in ma in () is used to call
the member function and output the total of each
grade achieved by the object stu de n t1 .
Task 4 Step 1
Cre at e a ne w p ro j e ct , Write a program that reads a product ID (Product 1 -
ca l l it El e ct ron i csOu t le 4 ) and the qu an t it y required.
t.
A swi t ch 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.
P ro d u ct 1: A sta b le
mu lt i vi b ra t o rs The output should show the cost per item, the VAT
@£ 15 .4 5 element and the total cost including VAT at 17.5% as
shown in Figure 61.
P ro d u ct 2: I nt eg ra t ed -
Ci rcu it Ti me rs @
£2 1. 78 .
P ro d u ct 3: E CL
@£ 15 .7 8 .
P ro d u ct 4: B i CMO S
di g it a l ci rcu i t s
@£ 34 .9 9 .
Figure 61
Not 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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct Wh il e . There is
one . cp p file and one .h Run the program. The output should be the same as
header file. Figure 62.
Figure 62
Task 2
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.
Not e : you will need to
use a method of
selection to establish the
highest and lowest
marks inside the while
loop.
Task 3
Cre at e a ne w p ro j e ct ,
ca l l it B MI .
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 4
OPTIONAL
Cre at e a ne w p ro j e ct ,
ca l l it a vg Te mp .
Seven temperature
readings are taken at
each of three locations in
Oxfordshire and stored.
Task 5
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.
Not e : The integer i used to control the loop and has
been declared within the brackets of the f o r loop (i nt i
= 0; ). This means that i only exists within the loop.
When the loop ends, i ceases to exist. This is called
the scop e of the identifier.
See appendix Scope 24.10 for more information.
Task 2
OPTIONAL
Cre at e a ne w p ro j e ct ,
ca l l it Bo o ks .
The program should
create three instances of
a class called B oo ks .
Create each of the
objects inside a fo r l oo p .
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 Do Wh i le 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 ecl i p se , o pe n t he
p ro j e ct Do Whi l e .
Establish how the do…
while loop can effect a
program written to
verify user input.
Figure 67
Establish why when using the do … wh i l e loop for
repetition a negative value (-19 as shown in Figure 67)
is established as being greater than zero.
Hin 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.
Cre at e a ne w p ro j e ct ,
ca l l it Fa ct o ri al
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, ve cto r and l i st 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.
No te : 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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct A rra y
Run the program adding five exam results. The
output should be similar to Figure 69.
Figure 69
Step 1
Examine the following statements
do ub l e E xa mMa rks[ 5 ] = {0 }; This statement
declares the array, setting it’s size to 5 elements and
explicitly initialising all elements to zero.
co u t <<"E n t e r Exa m Ma rk "<<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
Exa m Ma rk 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 nt eg e rs will be addressed from
element 0 t o 1 9 .
Exa mMa rks[ 0 ]… E xa mMa rks[1 9 ]
The first number will be entered into element [0 ] . The
last into element [ 19 ] .
cin >>E xa mMa rks[ i ] ;
This statement reads in the user input and stores the
values in the array elements of E xa mMa rks[ i] . i is
incremented within the fo 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 Na me 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 rra yNa me Ag 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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct Li ne a rS ea rch
Run the program; choose a number between 1 and
10 0 . The output should be similar to Figure 76.
Figure 72
Step 2
Examine the following statements
myA rra y[ i] = (1 + ra n d ()%10 0 ); This statement uses
the ra nd function, part of the <cst dl i b > header file.
ran d ()%1 00 produces integers in the range 0 to 99.
The function li n ea rS ea rch takes three arguments.
The array name, the size of the array, the third
argument is the search value.
if ( a rra y[ j ] = = va l ue )
ret u rn 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 ma i n () otherwise -1 is
returned.
The if selection statement if (e le me n t ! = -1 ) in
ma in () is used select the output indicating a
successful or unsuccessful search.
Task 2 Step 1
Create another program Create a project, call it Se a rch Co u nt V al
to output a count of the
Create a new source file S ea rch Cou n tV a l . cp p
individual numbers held
in an array. The Create a header file S ea rch Cou n tV a l .h
numbers in the array
should be randomly
generated. The output Step 2
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 ran d
function. The random numbers should be between 0
and 14 .
You will need to # in cl ud e <cst d l ib > for rand()
Step 3
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 4
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
Cre at e a ne w p ro j e ct , Fro m th e d i re ct o ry whe re yo u u np a cke d th e
ca l l it In se rt io nS o rt Cl a so u rce ma t e ria l s, op en th e f il e ca l le d In se rt io nS
ss o rt . 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
so rt [ 0 ] and so rt [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
so rt [ 2 ] and compares this to so rt [1 ] . If the value in
so rt [ 1 ] is greater than the value in so rt [ 2 ] the values
are swapped. The while loop is then used to compare
the value in so rt [ 1 ] to the value in so rt [ 0 ] .
This iterative process continues until all array
elements have been sorted.
Task 2 Step 1
OPTIONAL Add # in cl ud e "I n se rt io n So rt . h "
Add a new source file to Create an instance of the class S o rtA rra y myA rra y;
the project call it Create an array of 200 randomly generated numbers,
In se rt io nS o rt . cp p nu mbe rs[ i ] = (1 + ra nd ()%1 0 0 );
Step 2
Call the class member function
myA rra y. so rt A rra y(n u mbe rs, S I ZE );
Output the sorted array
co u t <<se t w(4 )<<n u mb e rs[ 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 3
Create a second object,
call it you rA rra 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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct Mu lt i Di mA rra y
Run the program adding 2 exam results for each of
There is one associated the two students. The output should be similar to
file Figure 76.
Mu lt i Di mA rra yMa i n . cp
p
Figure 76
Task 2 Step 1
Examine the code used Examine the following code segments
to write values to and
do ub l e E xa mMa rks[ 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 .
Not 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 2
Examine the following code segment used to read
values in to the array
for(int row = 0; row < 2; row++)
cout<<endl;
Step 3
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 3
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 4 Step 1
Cre at e a ne w p ro j e ct , A multi-dimensional array has been created and
ca l l it Mat ri xMa n i pu l at i initialised with 80 integers. From the directory where
on . you unpacked the source materials, open the file
This program will called mat ri x. t xt . 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 (ve c ) for example, by using the so rt
algorithm.
sort(vec.begin(), vec.end());
There are two important points to notice about the call to re ve rse . First, it is a
g lo ba l function (as are fi n d and so rt ) 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 eg in () to en d ()
(vec.begin() to vec.end()). re ve rse , like the other STL algorithms, is
decoupled from the STL container classes. The re ve rse algorithm can be used to
reverse elements in ve cto rs , in li st s (another container), and even elements in C
a rra ys .
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 it e ra to rs , 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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct Ve cto rDe mo
Run the program adding five exam results. The
There is one associated output should be similar to Figure 78.
file Ve cto rDe mo . cpp .
Figure 78
Step 2
Examine the following statements
#i n clu de <ve cto r>; This statement includes the
header file <ve ct o r> enabling the program to use the
class template ve ct o r . (templates allow the use of
generic functions that admit any data type as
parameters and return a value, more on this later.).
ve ct o r <do ub l e > Exa mMa rks (5 ); This statement
declares the vector to hold doubles and sets the initial
size to 5 elements.
Not 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.
cin >>E xa mMa rks[ i ] ; This statement reads in the
user input and stores the values in the vector slot i of
Exa mMa rks[ 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 Ve cto r. t xt and add it to
where you unpacked the Ve cto r. cp p immediately above the return statement ;
source materials, open
Run the program entering 5 numbers. Follow the
the file called
prompts and add an additional number to the vector.
Ve cto r. t xt . Copy the
The output should be as shown in Figure 79.
code and add it to
Ve cto r. cp p Examine the following statement
Exa mMa rks. p u sh _ba ck(t e st );
pu sh _b a ck() 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 3
Modify the program to
delete the last element
and output the vector
slots showing all values.
po p _b a ck() is the
member function that
can be used to delete the
last element in a vector.
Task 4
Cre at e a ne w p ro j e ct ,
ca l l it Ve cto rS o rt .
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
Cre at e a ne w p ro j e ct , In main() create a vector of penguin objects:
ca l l it
vector<Penguins> myPenguin(2);
Ve cto ro f Pe ng u in s .
Create a header file Print out the default contents of the vector
Pe ng u in 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 ma 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 in se rt () and
iterator it to insert 200 at the beginning of the vector
(i t ).
Note that an iterator is returned by the function
in se rt () that points to the newly inserted element.
Step 2
Examine the code shown in Figure 84
Figure 84
Step 3
Examine the code shown in Figure 85
Figure 85
Figure 86
Task 2
Add the code shown in
Figure 87 to the program
and using the i n se rt ()
member function add
the array to the nu ms Figure 87
vector. Output the
contents of the n u ms
vector to screen.
lists are declared indicating the type and number of elements in the following
way:
l i st <t yp e > l i st Na me ;
l i st <t yp e > l i st Na me (i n i ti a lS i ze );
l i st <t yp e > l i st Na me (i n i ti a lS i ze , e le me nt V a lu e s);
Examples are:
list<double> inNumbers; a list called i n Nu mb e rs with no initial size
to hold d ou b le s .
list<char> Name(20); a vector called Na me with an initial size 20 to
hold characters.
list<int> ExamMarks(4,6); a vector called Exa mMa rks holding integers
with initial size of 4 elements each with the
value 6
No te : In the following exercises you will use some of the l i st class member
functions found in the Standard Template Library (STL). Some of these are
b eg in () , e nd () , so rt () , and swap ().
The STL also includes a large collection of al go ri t h ms that manipulate the data
stored in lists. See section 24.14 for more detail.
Task 1 Step 1
In ecl i p se , o pe n t he Examine the statement shown in Figure 88
p ro j e ct Me rge , and
examine the program
works.
Figure 88
This statement creates two lists to hold doubles,
li st O ne and li st Two .
Figure 89
This statement creates a third list and initialises it
with two elements each holding 9.69.
Step 2
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 st is bidirectional. Note
that the iterator type for a ve cto r is random access.
The twelve statements following the iterator
declaration use the class member function
pu sh _b a ck() to add new elements at the end of each
list.
The pu sh _b a ck member function is common to
vectors and lists.
Step 3
Examine the statement shown in Figure 91
Figure 91
This statement uses member function so rt () to sort
li st O ne .
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 li st O ne . so rt () provided.
Step 4
Examine the following statements
Figure 92
list iterator i t is used to loop through the elements of
the list.
li st O ne .b e gi n () returns an iterator to the beginning
of the list.
li st O ne .e n d () returns and iterator to the end of the
list.
it and the dereference operator * are used to output
the values in the vector, *i t .
Step 5
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.
NO TE: This empties the second and increases the size
of first list.
Task 2 Step 1
In this task you are The li st Th ree ob ne ct is re si ze d to to the same size
asked to examine as l i st Two using the list member function re si ze () so
ma in Me rg e. cpp which that the list can hold all the elements copied.
copies the contents of
Arguments to re si ze are the size of l i st Two . The
li st Two to li st Th ree .
li st Two member function si ze () is used to get this
Note that cop y is an value.
algorithm not a member
Copy the contents of li st Two to l i st Th re e
function of the list class.
The syntax for the copy algorithm is:
it e ra to r cop y( i te ra t o r st a rt , i te ra t o r en d, it e ra to r
de st in at i on );
The return value ‘it e ra to 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
Cre at e a ne w p ro j e ct , The function prototype you create should be similar to
ca l l it Sa la ry . Name
the source file void CalcSalary(double grossSal, double IT,
Sa la ry. cp p . double NI = 5.0);
Step 2
Create a function call it ca l cS a la ry
The function will receive three arguments, the
definition is shown below
vo i d Ca l cSa l a ry(d ou b le g ro ssPa y, do ub l e I T,
do ub l e NI )
The formula for calculating the take home pay is:
Ta ke Ho meP a y = (g ro ssP a y*(1 -NI ))*(1 - I T);
Task 3
ONLY ATTEMT THIS IF
YOU HAVE
COMPLETED
CHAPTER 7
Create an ob je ct for
each member of staff.
Create separate member
functions to change the
rate of NI and I n co me
Ta x .
Task 1 Step 1
In ecl i p se , o pe n t he Run the program. The output should be the same as
p ro j e ct Te mp e ra tu re s shown in Figure 94.
Ret V al u e s and modify
the program.
Figure 94
Step 2
Examine the function prototype
in t Ft o Cen t (i n t t e mp , in t 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
ret V a lu e = Ft o Cen t (I _fa r, cho i ce );
The function call Ft o Cen t () passes arguments I _f a r
and choice. The value returned is assigned to
ret V a lu e
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.
in t Ft o Cen t (i n t I Te mp, in t in d ) {}
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 nd
and if selection.
The statement I _f a r = (I Te mp - 32 ) *5 / 9 ; is used
to calculate the temp in centigrade
The statement I _f a r = sta t i c_ca st <i n t >(I Te mp *
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 ma i n ().
Not e : The data being returned must be the same data
type as defined in the function prototype. In this
example an integer.
Task 2 Step 1
(REQUIRES Modify the program so take home pay is returned
COMPLETION OF 27) from the function and output to screen from within
ma in () .
Open the Sa la ry 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 3
OPTIONAL
Create a new project, call
it Ret u rn E xp e rRe su l t s
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,
Ret u rn E xp e rRe su l t s ,
Exe rci se 2 8 Ta sk 3.
Create a class call it
Exp e ri men t re sul t s in a
new file called
Ret u rn E xp Re sul t s.h .
The values read in to
ma in () should be passed
to a function called
rea d Nu mbe rs( ) i n
ma in () .
From within the function
rea d Nu mbe rs( ) create
an object of the class
Exp e ri men t re sul t s .
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 ma i n ()
from the function
rea d Nu mbe rs( ), then
output to screen.
Task 1 Step 1
Create a new project, call Create a new project, call it call it A rra yRet u rnV a lu e
it A rra yRe tu rn V al u e .
Create a function prototype do ub l e
Pass an array to a ca l cA ve ra g e (d o ub l e E xa mMa rks[ ] , in t nu m);
function and read in five Exa mMa rks[ ] is the array being passed. As with
numbers. passing variables, it is not strictly necessary to pass
Calculate the average the name of the argument, just its type. This could
value in the array, return have been written as ca l cA ve rag e (d ou b le [] , in t
this to ma in () and nu m); However, it is useful for future reference as it
output to screen. helps explain how the function works.
At the end of the It is also necessary to pass the size of the array. nu m
program output the is the number of elements in the array, it’s size.
values in the array from
Step 2
within ma in () .
Within ma i n () declare the array and initialise the
elements to zero with the following statement do ub l e
Exa mMa rks[ 5 ] = {0 };
This declaration explicitly initialises the first element
to zero and implicitly initialises the remaining four to
zero
Step 3
Create a function do ub l e ca l cA ve rag e (d o ub l e
Exa mMa rks[ ] , i n t n u m) { }
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 ma in () with the
following statement
ave rag e = ca l cA ve rag e (E xa mMa rks, 5 );
Step 5
At the end of ma i n () add the statements
fo r(i n t i = 0; i < 5 ; i ++)
co u t <<"E xa m Ma rk Nu mbe r "<<i + 1 <<" is
"<<E xa mMa rks[ i ] <<e n d l <<e n d l;
Step 6
Explain how it is possible at the end of the program to
output from within ma in () all the values in the array
entered within the function
In previous exercises when parameters (variables)
were passed to functions the function received a
va l ue . When a va l ue 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 va l ue in it are lost.
However, the array in this exercise was initialised in
ma in () 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
ca l cA ve ra g e (E xa mMa rks, 5 ) the name of the array,
Exa mMa rks is passed.
Task 2
Modify your program so
that the calculations are
done in a class file. Pass
the array to the class
using a constructor.
Task 3
Go back to Exercise 21
and modify the header
file to sort the array
passed using the global
vector function so rt () .
You should be able to
replace the whole
member function
functionality with one
statement.
Not e that you will have
to change the class
member function name
from so rt 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
so rt A rra y() .
Task 4
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
A rra yMul t Re tV a l .
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
/*a dd de po si t s i n h e re */
Step 2
Create a second function vo id pa ssBa l an ce s
(do ub l e B a la n ce [ ] [ co l Si ze ] ,i n t rS ) after ma i n ()
Calculations to establish the interest and balance for
each customer should be done in the inner loop
(co lu mn ) of the array search. The following
statements will establish the deposit, interest and
total for each deposit
de po si te d += Ba l an ce[ r] [ c] ;
in t e re st +=B a la n ce [ r] [ c] *0 . 05 ;
to ta l +=(B a l an ce [ r][ c] *(1 + 0. 05 ));
The calculations to total all deposits need to be done
in the outer loop (ro ws ) of the array search
OA de p o si t ed += d ep o si t ed ;
de po si te d = 0 ; / *re set th e a mou n t d ep o sit ed f o r
ne xt cu sto me r*/
OA i nt e re st +=i n t e re st ;
in t e re st = 0; / *re se t th e i nt e re st f o r ne xt
cu st o me r*/
OA t ot a l +=t o t a l;
to ta l = 0;
Step 3
Call the functions from within main() with the
following statements.
ge t Dep o sit s(B a la n ce , ro wSi ze );
pa ssBa l an ce s(Ba l an ce , ro wS i ze );
Task 2
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 ecl i p se , o pe n t he Run the program. The output should be the same as
p ro j e ct O ve rl oa d in g Fu shown in Figure 96.
nct i on s. Examine the
program structure.
There is one source file
O ve rL oa d in g Fu n ct io n s
. cp p.
Figure 96
Step 2
Examine the function prototypes
void FtoCent(int temp);
void FtoCent(double temp);
Step 3
Examine the statement
in Va l ue = t ou pp e r(i nV a lu e ); t ou pp e r is a member
function in header file <cct yp e > that changes the
input char to upper case. Using t ou pp 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 vo id Fto Ce nt (d o ub l e I Te mp )
used to convert a double value read into centigrade.
The statement cou t <<f i xed <<se t p re ci sio n (2 );
This statement sets the stream manipulators, f i xe d
and setprecision. Another stream manipulator used
in this function is se t w . The header file <i o man 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 co u t <<se 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.
The statement cou t << f i xe d << set p re ci si o n (2 ) <<
se t w(5 ) << ITe mp ; sets the precision of the following
Task 1 Step 1
In ecl i p se , o pe n t he Run the program, adding data as requested. The
p ro j e ct Fu n ct io n Te mp output should be the same as shown in Figure 97
la t e . Examine the
program structure.
There are two associated
files:
Fu n ct i on Te mp la t e -
Ma xi mu m. h
Fu n ct io n Te mp l a te -
Ma xi mu m. cp p.
Figure 97
Step 2
Examine the header file Fu n ct io n Te mp l a te -
Ma xi mu m. h
T ma xi mu m( T val u e1 , T va lu e2 , T va lu e 3 )
Task 2 Step 1
Cre at e a ne w p ro j e ct , Create two files in the project. A class definition and
ca l l it Fu n ct io n Te mp l a t the client code.
eA rra ys.
In the header file create the class Sh o wA rra y
In the class create a function template as shown in
Figure 98 (or copy from FunctionTemplate-
Arrays.txt)
Figure 98
Step 2
In ma 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 ho wA rra y with the
statement S ho wA rra y mySh o wA rra 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
De cl a ra t i on s:
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 ge is a pointer, he ig 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 ul l po in t e r .
No te :
When the * is used in a variable declaration it indicates the variable being
declared is a po in t e r and not a va l ue .
But do beware, when the * appears before a pointer variable elsewhere in the
program it acts as an operator, called the d e re f e ren ce o pe ra to 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 dd re ss of o pe ra to 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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct Po in t e rs .
There is one associated Run the program. The output should be the same as
file, Po in t e rsMa in . cpp . Figure 100.
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.
in t *x_p t r = & x; This is x_p t r pointer
declaration and initialisation.
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 ecl i p se , o pe n t he Compile the program, sorting any compilation errors.
p ro j e ct Po in t e rA ri th m
et i c . There is one Run the program. The output should be the same as
associated file, Figure 101.
Po in t e rA ri th me t i cMa in .
cp p .
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.
in t *x_p t r = in t A rra y; this is the pointer declaration
and initialisation. Note: The name of the array is the
address of the first element.
fo r (i = 1; i <5; i ++)
{
x_pt r++;
co u t <<"Th e V AL UE sto re d i n E LE ME NT
"<<i +1 << " i s " <<*x_p t r <<e nd l ;
}
In ma in () create an array
of 20 random numbers of
type double.
Task 3 Step 1
Cre at e a ne w p ro j e ct , Fro m th e d i re ct o ry whe re yo u u np a cke d th e
ca l l it A rra y_Al g o rit h m so u rce ma t e ria l s, op en th e f il e ca l le d A rra y_Al g o
. ri th m. t xt
Use STL global functions Replace the default source file in the project with
to manipulate an array. A rra y_Al g o rit h m. t xt
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 ecl i p se , o pe n t he I n e cli p se, op en th e p ro je ct He ad e r. If you do
p ro j e ct He ad e r . There not have this project, go back to Exercise 13 and
should be one associated complete the task.
source file: O xSt u de n t s. h .
Add a new Source file to the project, File | New |
Modify the header file to Source File
create class definitions.
Save and name the file O xS t ud en t s. cp p .
Create an additional file
detailing the member
function definitions that Step 2
represent the Copy the class definition code from O xSt u de n t s. h
implementation of the file and paste it into the O xSt u de n t s. cpp file.
class.
Change the code in O xS t ud en t s.h so there is no
implementation, see Figure 104
Figure 104
Step 3
Add the directive #i n clu de "O xS tu de n t s. h " at the
top of O xS t ud en t s. cp p
Compile the program
You should get a compilation error indicating a
redefinition of class O xSt u de n t s . The class has
already been defined in the .h file and a class
cannot be defined twice.
Step 4
Remove the class definition by removing the line
cl a ss O xSt u de n t s and the closing curly brace and
semi-colon at the end of the file
Remove p ub l i c:
Change the function headers to match Figure 105 .
Figure 105
Notice that di sp la yNa me is now preceded by the
class name, O xSt u de n t s and :: the b in a ry sco p e
re so lu t io n op e ra t o r . The member function is now
related to the separate O xS t ud en t s class definition
that contains the class data members and member
function definitions.
Compile and run the program
Task 2
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 ecl i p se , o pe n t he Open the P a ssB yRe f Fu n c project.
p ro j e ct Fu n cRe fV a lI n l in e
. Step 2
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 3
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 4
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; zRef is a reference to z .
References must be initialised when declared.
Figure 108
Step 5
Examine the statement shown in Figure 109. :: is
the un a ry sco pe re so l ut i on o pe rat 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 6
Examine the rest of the program and then add zRef
= & 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 st af f object and
d ou bl e .
Figure 112 shows the function call with an instance of S ta f f called Joh n being
passed with a d ou bl e 10 .
Figure 113 shows the function body. It receives the two parameters. The staff
object e mp is set to the same value as John and amount is set to 10. e mp is then
modified but the modification has no effect on John as e mp is a separate object.
When the function exits e mp is forgotten and John doesn’t get a raise, most
unsatisfactory.
I n t he fu n ct i on ra i se S al a ry(), e mp is a value parameter because it is a variable
initialised with a value supplied by the caller. We want e mp to refer to the
instance object Jo h n . We also need the salary of Joh n to be updated with
changes calculated within the function. To achieve this we make e mp a
re f e re n ce 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 ecl i p se , o pe n t he Open the S ta f f project.
p ro j e ct Ref S al a ry .
Examine the structure of
project and establish how Step 2
the program works. Run the program. The output should be as shown
in Figure 114.
Modify the program to use
reference parameters so
e mp is a reference to an
existing instance object
Jo h n .
Figure 114
Obviously there is a problem somewhere; John
Black has not received the payment with the
increase in salary.
Step 3
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 4
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. Ref e ren ce s
a re co n st an t by de fa u l t .
d ou bl e Sh ap e: : ge t A rea () co n st
{
re t u rn a rea ;
}
Task 1 Step 1
In ecl i p se , o pe n t he Look at all the files in the project and modify the
p ro j e ct Ref S al a ry2 program so that co n st 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 2
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.
Vertebrates
Placental
Monotremes Marsupials
Mammals
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.
Ma mma l s.
Mammals are vertebrate animals that are endothermic (warm blooded), have hair
on their bodies, and produce milk to feed their babies.
P la ce nt a l Ma mma l s
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.
Mo no t re me s
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.
Ma rsu p ia l s
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
cl a ss used previously.
cl a ss Ca t : p ub l i c b ase _cl a ss_n a me is the essential syntax for inheritance.
The syntax indicates that the class (Ca t ) will contain all public and protected (see
section 15.3) data members of the base class (P la ce nt a l Ma mma 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 nca p su l at i on .
p ri vat e : A data member or member function declared in a p ri vat e
section of a class can only be accessed by member functions and f rie nd 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 ro te cte d : A data member or member function declared in a p ro t e ct e d
section of a class can only be accessed by member functions and f rie nd s of
that class, and by member functions and friends of d e ri ve d classes. See
section 15.7 for more information on f ri en d s .
One of the problems with using p ro t e ct e d data is that derived classes can
modify the base class data members directly (Ba se Cla ss: : Dat a Me mbe 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 man ag e r. cpp and sta f f. cp p that contain the
detail of how the member functions work.
Step 4
Open man ag e r. h . Examine the class definition
cl a ss Ma na g e r : pu bl i c St a ff .
The : colon character denotes inheritance. The
keyword pu bl i c is required. However, if we omit
p ub l i c the class definition will still compile.
Ma na g e r will still inherit from S ta f f but will
inherit privately. This means that only the member
functions of Ma na g e r get to call the member
functions of S ta f f .
Whenever you invoke a S ta f f method on a
Ma na 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 ma na g e r.h has p ub l i c member
functions and p ro t e ct 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 osi t io n and nu mS ta f f .
The separate source code file ma na g e r. cp p
contains the detail of the member function
implementation.
Note the use of the pre-processor directive
# in cl ud e "st a f f .h " at the top of the file. This is
needed as the class ma na g e r inherits from sta f f .
Without it the ma na g e r class does not know about
the sta f f class members
Step 5
Open the file ma na g e r. cp p . The separate source
code file man ag e r. cpp contains the detail of the
member function implementation and how the
functions work.
Note the use of con st after the member functions.
Constant member functions that never change a
class member value should be declared as con st .
See Appendix 24.18 for more detail.
Step 6
Open the file st af f .h . The interface sta f f. h has
p ub l i c member functions and p ri vat e data
members. Private data members can be accessed
via member functions of it’s own class or member
functions of the derived class ma na g e r using base
class member functions.
Note the se t member functions that are used by
the derived class to set the data members in the
base class.
There are also five co n st member functions to
return data from the base class object.
Step 7
Open the file st af f . cp p . The separate source code
file st af f . cp p contains the detail of the member
function implementation for the base class and
details how the functions work
Note the use of con st after the member functions.
Again, constant member functions that never
change a class member value should be declared as
con st .
Step 8
Open the file ma na g e rMa in . cpp . This is the main
file in which we create an instance of the derived
class manager called ma n1 .
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.
Ma n1 . set Na me (n a me );
The output is produced by calls to the instance
methods of the class, ex. Ma n1 . ge t Na me (),
Ma n1 . ge t nu mS t af f ().
Note that these member functions are functions in
the base class st af f , not the derived class.
Figure 121
Step 2
Change the class header file ma na 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 St a ff (); to
accept the five parameters being passed from the
base class initialiser list.
Step 4
Modify the statement Ma na g e r Ma n 1 (man Ti t le ,
nu mS ta f f ); in ma na g e rMa in () used to create and
initialise the instance of Man ag e r class. When
creating the instance of Ma n1 you will have to pass
all seven arguments.
Step 5
Remove the five statements from ma na g e rMa in ()
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 cli p se, op en th e p ro je ct S ta f f file in the
directive to the st af f .h file I nh e ri ta n ce S ta f f folder.
in the project used in
Add a preprocessor wrapper to the sta 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 (. cp p ) that
to use the program you 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.
Ad mi n i st ra t i ve sta f f .
Remember to use a member initialisation list.
Ad mi n staff share all the
base class data members
attributes and can therefore
be treated as a derived class
of class sta f f .
Modify the St a ff 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
Be aware that overriding base class methods can hide ove rl oa de d methods in the
base class. An overriding method in the derived class will hide all overloaded
methods with the same name in the base class. In below, both of the mo ve s()
methods in the base class are hidden even though they have different arguments.
Note that base class methods can be called, MyCa t. Ma mma l : : mo ve s(), by
explicitly stating its class name, then the member function name separated by :: ,
the sco p e o pe ra to r. It can be useful to call base class methods in this way that
have been overridden by derived class methods.
Task 1 Step 1
In ecl i p se , o pe n t he Open O ve rRi de Ba se CM project, compile and run
p ro j e ct O ve rRi d eB a se Cla the program. The output should be as shown in
ssMet h s . Figure 124.
In ecl i p se , o pe n t he
p ro j e ct O ve rRi d eB a se Cla
ssMet 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 Ma mma l and a
derived class Ca t .
The base class has overloaded functions mo ve s()
and mo ve s(4 ) .
The derived class also has function mo ve s() .
When an instance of Ca t is created and the
function mo ve s() called this overrides both of the
overloaded mo ve s() functions in the base class.
There appears to be no way that a Ca t object can
get access to the overloaded base class function
mo ve s(i n t ) .
Step 3
In ma i n. cp p change the statement
MyCa t. mo ve s(); to MyCa t. mo ve 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 mo ve s(i n t ) is hidden to any
object of the derived class Ca t .
Step 4
Examine the statement
MyCa t. Ma mma l : : mo ve s(4 ); Here we are calling
the base class function mo ve s(4 ) by explicitly
stating the instance, base class name then member
function separated by the :: sco p e o pe ra to r .
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 Hu mP l a cMa mma l
Hu mPl a cMa mma l .
.
You will need to create
three . cp p class files and
then complete the detail Step 2
member function Fro m t he di re cto ry wh e re you un pa cked t he
implementation. sou rce ma te ri a l s, o pe n t he fi l e ca ll e d Hu mP l a
You will need one Hu ma n , cMa mma l (S t ud De f in i t io n s) . There are four files
one Pl a ce n ta l Ma mma l you will need.
and a Ma mma 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 ma in () 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 Hu man , P la ce nt a l
are overridden and you may Ma mma l and Ma mma 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 ma 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 Hu ma 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. "wa l k e re ct on
t wo f ee 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 (. cp p ) to implement
member function functionality.
Step 6
Using the ma i n function file create an instance of
the Hu man 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 ecl i p se , o pe n t he Open Fri e nd sFu n ct i on project, compile and run
p ro j e ct Fri en d sFu n ct io n . the program. The output should be as shown in
Examine how a function can Figure 126.
be used to access private and
protected data members of a
class.
Figure 126
Step 2
Open the file ma in . cp p .
Before ma in () there is a function prototype.
Re ct a ng l e d up l i ca te (Re ct an g le in re ct );
The prototype name is duplicate, it accepts a
Rectangle object as an argument and returns a
Rectangle object.
Step 3
Examine the statement Re ct a ng l e re ct (2, 3 );
Here we are creating an instance of Re ct a ng l e
class and initialising the data members width (2)
and height (3).
Beneath this a second Rectangle object is created
Re ct a ng l e re ctb ; using the default constructor.
The next statement of interest is re ct b =
du pl i ca te (re ct ); Here we are calling the function
duplicate and passing the object re ct . This object
has data members wid t h (2) and he ig h t (3).
Step 4
Examine the Re cta n gl 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 Re ct a ng l e object is
created, Rectangle rect; The data members of
the object i n re ct are accessed, doubled, then
assigned to the new object i n re ct . This is unusual
as p ri vat e and p ro te cte d members of a class
cannot normally be accessed from outside the
same class in which they are declared.
Step 5
Open re ct an g le .h . Note that in the public section
of the class definition the function du pl i ca te has
been declared as friend of the Rectangle class,
f rie nd Re cta ng l e d up l i ca t e (Re ct an g le );
Declaring a prototype of the external function
within the Rectangle class, then preceding it with
the keyword f rie nd , means the function can access
the private and public members of the class.
Task 1
Modify the program in the
Fri en d s Fu n ct i on project
by adding a new class
Tri an g le . Add a definition
and source file. The data
members are ba se and
he ig h t .
Add a constructor,
destructor and member
functions to set the data
members and get the area.
Add another f rie nd function
and prototype to ma in () .
Call the function t ri an g le .
The area of a triangle can be
calculated as half the base
multiplied by the height.
Add an additional function
prototype to the t ria ng l e
header file.
Output the area of the new
t ria ng l e object using the
f rie nd function to access the
p ri va te data members of the
class.
Add an additional function
prototype to the t ria ng l e
header file.
Task 1 Step 1
In ecl i p se , o pe n t he Open ma i n. cp p and examine the statements
p ro j e ct Fri en d Cla ss . 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
Re ct a ng l e and one S qu a re .
Instance sq r uses the member function
se t S id e (4 ) to set the dimension of the square.
Instance re ct calls the con ve rt member function
and passes the object sq r .
Step 2
Open squ a re .h . Examine the statement:
friend class Rectangle;
This statement declares class Re ct a ng l e as a
friend of S qu a re . Re cta n gl e can now access
private and protected data members of instances
of the S qu a re class.
Not e : Friendship is one way.
Re ct a ng l e is a friend of Sq ua re 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.
Not e : Frienships are not transitive. You cannot
have a class as a friend of another friend class
unless explicitly specified.
Step 3
Open re ct an g le . cp p and examine the function
shown in Figure 128.
Figure 128
Function co n ve rt is passed a parameter of type
Sq ua re (a ) .
In the statement width = a.side *2; a is the
ob je ct and sid e is the d at a me mb e r of the class
Sq ua re .
So the p ri va te data members (si de ) in class
Sq ua re have been accessed by public member
functions of the Re ct a ng l e class. These have
been assigned to the p ri vat e data members of the
Re ct a ng l e class, wi d th and he ig h t .
When the Re cta n gl e member function
re ct . a rea () is called, the width and height of the
Sq ua re object are used to calculate the area of the
rectangle.
Step 4
Open re ct an g le .h . Notice at the top of the file the
statement #include "square.h". This is
included as we make reference to the S qu a re class
in the function con ve rt ().
Comment out the # in cl ud 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 Tri an g le .
Add a function definition
and source code file.
The class will have data
members wid t h and h ei gh t
and a member function
ge tA re a () returning the
area of a triangle.
The area of the triangle can
be calculated as ½ the width
*height. The wid t h and
he ig h t are the p ri vat e data
members of the Re ct a ng l e
class.
Do these calculations in a
function in Tri an g le that
can be called from ma in () .
Class Tri an g le will have to
be declared as a friend of
Re ct a ng l e .
The t ria ng 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 (in he ri t an ce ). When we
include class objects as members of other classes we call it co mp o sit i on or
a gg re ga t io n .
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 ub 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 ref e re n ce 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 ecl i p se , o pe n t he Compile and run the program. The program
p ro j e ct Co mpo si t io n . should look the same as Figure 129.
Examine the code to see how
Dat e class objects are used
as data members of the
E mp l o ye e class.
Figure 129
Step 2
Open ma i n. cp p and examine the statements
shown in Figure 130.
Figure 130
The first two statements create two Dat e objects
bi rt h and h i re . 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 mp l o ye e called st af f and passes the employee
first and last names and the two Da te class objects
to the class constructor.
The seventh statement calls the p ri nt method
using the sta f f object.
Step 3
Open E mp lo yee . h class definition. This is shown
in Figure 131.
The first statement is the class constructor.
Two st rin g s are being passed to the constructor
representing the first and last names.
Con st Da t e & is passing a reference to the Dat e
object for the DOB. The Da te object is co n st and
cannot be changed and represents the birth date.
Con st Da t e & is repeated (for the date hired) and
the reference is passed to the data member for
hi re Da te .
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 Da te .
Note the use of #i n clu de "Da t e. h " in the
E mp l o ye e class definition.
The E mp l o ye e class is using objects of the class
Dat e so must include the Da te class definition.
Doing this means the compiler knows about the
Dat e class when the objects are passed via the
constructor in E mp lo yee . cpp to the Da te
constructor.
Step 5
Open E mp lo yee . cpp . Examine Figure 132.
This shows the class constructor using a me mb e r
in i t ia l i se r l i st to pass initialiser reference values
to the Da te member objects b i rth Da t e and
hi re Da te 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
hi re Da te . p rin t (); statement.
The instance object hi re Da te is a reference to the
instance (hi re ) passed from main to Employee.
The reference is used in the member initialiser list
(d at e Of Hi re ) to initialise the member object
hi re Da te , hireDate(dateOfHire).
hireDate.print(); calls the Da te member
function p rin t () of the instance h i re of the Dat e
class.
The p rin t () function of the Dat e class object
outputs the date the employee was hired.
Ina similar way birthDate.print(); calls the
Dat e member function p rin t () of the instance
bi rt h of the Dat e class.
Figure 133
Task 1
Create a new project, call it
St ud e nt s .
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:
Na me;
da te O fB i rt h ;
da te O fE n ro l men t ;
co u rse Na me;
Figure 134
Create instances of the class
St ud e nt 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
A TM S cre en .
You will need to create three
classes, A TM, Scre e n &
Ke ypa d .
Figure 136 shows a class
diagram with composition of
classes.
A TM is using objects of class
Scre e n and K e yp ad as
members. Class A TM has a
composition relationship
with class Scre e n and
Ke ypa d . Figure 136
A member function of the
Scre e n class is used to
output prompts to screen
and a member function of
Ke ypa d used to get user
input.
In the ma in () function
create an instance of the
A TM cl a ss .
The A TM class should define
a Scre e n & Ke ypa d object
as private members of the Figure 137
A TM class.
Use member functions of
Scre e n class to output user
information. All input
should be via K e yp ad class
member functions.
Verify the account and PIN
numbers read in are valid
using member functions of
class A TM .
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 cree 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 pe ra to rs 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 pe ra to r
o ve rl o ad i ng . 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 ecl i p se , o pe n t he Open ma in Co mp le x. cpp . Run the program and
p ro j e ct Op e rat o r see how it works.
O ve rl oa d in g pl u s .
Examine how to overload
the addition + operator.
Figure 139
Examine the code shown in Figure 147.
Here we are creating four objects of the CV e cto 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 co mp l e x. cp p .
Figure 141
Examine the function named op e ra t o r+ shown in
Figure 141.
o pe ra to r+ indicates the + addition operator is
being overloaded.
Step 4
Examine the function op e ra t o r+ .
The function o pe ra to 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 CV e cto r instance
object data members.
Compile and run the
program and explain what
is happening.
Task 1 Step 1
In ecl i p se , o pe n t he Open ma in . cp p . Run the program and see how it
p ro j e ct O ve rl oa d St re a m works. The output should be the same as Figure
In se rt io n . 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 Pa rt Nu mbe r have been created,
p a rt and p a rt2 .
The statement cin >> p a rt is passing the i st rea m
object cin and the instance object pa rt to the
overloaded function op e ra t o r>> .
The statement co u t << pa rt is passing the ost re a m
object co u t and the instance object p a rt to the
overloaded function op e ra t o r<<.
Figure 144
Step 3
Open the implementation file S pa re Pa rt s. cpp and
examine the code shown in Figure 144.
The overloaded op e ra t o r>> function returns a
reference to an i st re a m object and takes two
parameters by reference:
These are an i st rea m object and a user-defined
type.
The user-defined type 'P a rt Nu mb e r ' is not passed
as a con st parameter because the input operation
can modify it.
The body of the overloaded op e ra 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 Sp a reP a rt s. cp p
The overloaded o pe ra to r<< function returns a
reference to an o st rea m object and takes two
parameters by reference:
These are an ost re a m object and a user-defined
type.
The user-defined type 'pa rt Nu mbe r ' is passed as a
con st parameter because the output operation
doesn't modify it.
The body of the overloaded o pe ra to r<< function
inserts members of the user-defined object into the
o st rea m object.
Figure 146
Step 5
Open the definition file S pa re Pa rt s. h and
examine the code shown in Figure 146.
The two overloaded input and output operator
functions are declared as f ri en d s because they
need to access non-public (private and protected)
class data members (Ma nu f a ct u re r etc) directly as
the class does not have any get member functions.
The two overloaded functions are not part of the
class Pa rt Nu mbe r but added as prototypes of the
external functions within the class definition in
S pa re Pa rt s. h .
See section 15.7 for more information on friend
functions.
Task 1 Step 1
In ecl i p se , o pe n t he Open In he ri t an ce Ma in . cpp .
p ro j e ct In he ri t an ce
Dyna mi c
Examine how to
dynamically allocate
memory for a Ca 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 pt rCa t that
allocate and delete
will point to a Cat 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 pt rCa t and the
arrow notation to point to the member function
se tA ge () . A parameter 5 is passed. This sets the
data member a ge in the base class to 5.
The second statement uses the pointer and arrow
notation to set the data member wei g ht 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 In he ri t an ce Open In he ri t an ce Ma in . cpp .
Dyna mi 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 ecl i p se , o pe n t he Open the project st rca tS t rn cat and run the
p ro j e ct st rca t S t rn ca t . 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 ge t li n e () . ge t li n e () will
read into the array 25-1 characters.
The ending n ul l ch a ra cte 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 re p la ce () 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
st rcp 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 st rto k to Pt r and points to
the first character in the array a . st rto 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. st rt o k saves (st at i c va 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 st rt o k .
Subsequent calls to st rt o k have NULL as the first
argument.
The NUL L argument indicates st rto k should
tokenise from the saved pointer location in array a .
When there are no tokens remaining st rt o k returns
NUL L .
NOTE: st rt 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
We l co me .
Task 1 Step 1
Copy your folder con st ch a r *co n st , signifies a constant pointer to
Co mpo si t io n from constant data.
Exercise 50 and save it as
The class implementation file (. cpp ) should use
Co mp CS t ri n g .
functions:
Modify the program to use
st rl en to get the length of the strings read and,
pointer based strings.
st rn cp 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
Fro m th e d i re ct o ry whe re Using the program in Exercise 57 as a guide
yo u un pa cke d th e sou rce initialise an array with the data in the Java.txt file.
mat e ri a l s, op en th e f i le
ca l l ed Ja va .t xt . The program should allow the user to search for a
user input word.
The text file contains a
paragraph of text that we We also need to establish the following:
need to analyse. Number of characters in the complete paragraph.
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 vi rt ua l functions
and b ase 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 vi rt ua l function through a ba se
cl a ss p oi n te r or re f e re n ce . 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 ba se class. Its functionality
can be over-ridden in its d e ri ve d classes and the whole function body replaced
with a new set of implementation in the d e ri ve 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 wa 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 ba se cl a ss p oi nt e r , we need all three
classes to have fl y and wal k functions.
The secret to using polymorphism in C++ is to create a vi rtu 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 ecl i p se , o pe n t he I n e cli p se, op en th e p ro je ct B i rd s . Compile
p ro j e ct Bi rd s . 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 ba se class
pointer and assigning a ref e re n ce to a derived
Understand how vi rtu a l class object it is possible to access the member
member functions used in a functions of the derived class.
ba se class can have their
functionality over-ridden in It also shows how by using vi rt ua l functions and
the d e ri ve 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 al k() functions and
implementation in the t al k() is a vi rtu a l function in the base class then
derived class. the derived class t al k() functions will override the
base class function.
Figure 160
Step 2
Open ma in . cp p . Examine the statements shown in
Figure 161.
Figure 161
Duck myDuck; creates an object of type Du ck
called myDu ck .
The next statement creates a ba se cl a ss pointer
P t rb of type Bi rd . Assigned to the base class
pointer is a reference to a Du ck object, myDu ck .
It is now possible to use polymorphism to invoke a
vi rt ua l function in a derived class through a base
class po in t e r or ref e re n ce .
C++ dynamically selects the correct virtual
function in the derived class using the re f e re n ce
object assigned to the ba se class pointer.
The vi rt ua 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 rd. 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 vi rt ua 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 wa l k().
Step 4
Open the base class implementation file b i rd. cp p .
Examine the code shown in Figure 163.
There is a class constructor, a destructor and two
member functions.
The base class functions are wa l k() and the vi rt ua l
function t al k().
The t al k() function in this base class will be
overridden by the t al k() functions in the derived
classes P ig e on and Du ck 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 Du ck class definition file du ck.h .
Examine the code shown in Figure 164.
Figure 164
The first statement declares a function to override
the base class function talk().
No te : It is not strictly necessary to add vi rt ua 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 wal k().
However, the function wa 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 Du ck
object, but wal k() is not a virtual function therefore
the base class function wa l k() will always be called.
Only member functions that are vi rt ua l will be
overridden by the derived class function. Function
wa l k() is not a virtual function so the pointer will
use the base class function wal k().
Step 6
Open the Duck class implementation file
duck.cpp. Examine the code shown in Figure 165
The two functions are ta l k() , the vi rtu a l function
that will override the base class function and
wa l k().
Derived class wal k() can not be called as the base
class pointer (P t rb ) used to access the member
functions cannot be used to access a non-virtual
member function.
Figure 165
Step 7
Examine pi ge o n. h function definition and
p ig eo n . cp p the implementation file.
These derived class member functions work in a
similar way to the derived class Du ck 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 wa l k().
There are two ways to do
this.
Firstly it is possible to make
the wa l k() functions
vi rtu 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 rd . This is a
base class pointer and by
using this base class pointer
and vi rtu a l functions we
can gain access to derived
member functions that are
also vi rt ua l .
This idea of using a base
class pointer is great for
polymorphism but prevents
us accessing non-virtual
member functions. What
other kind of pointer can be
used to access member
functions of the Du ck
class?
Task 1 Step 1
In ecl i p se , o pe n t he Run the program.
p ro j e ct Po l yg o n .
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 re ct .a re a () and t rg l . a rea ().
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 ab st ra ct classes.
A b st ra ct classes are usually used as ba se classes. Abstract classes can never be
instantiated and require the derived classes to complete the class before
instantiation.
If there is an a bst ra ct class then there is a good chance there is also a co n cre te
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 bst ra ct class Sh ap e and then derive concrete classes with the
specific detail necessary to instantiate an object. The concrete classes might be
Ci rcl e , S qu a re and Tri a ng l e . Figure 167 shows a primitive inheritance
hierarchy for shapes.
Figure 167
In Figure 167 we can define Sh ap e as an ab st ra ct class. It would be extremely
difficult to define the data members and member functions for a sh a pe 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 Ci rcl e , Re cta n gl e and Tri an g le .
To create an abstract function we need to make one of its vi rt ua l functions a p u re
vi rt ua l function by placing “= 0 ” in the declaration. This is known as the pu re
spe ci f ie r .
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 ecl i p se , o pe n t he I n e cli p se, op en th e p ro je ct P u re V i rt ua l .
p ro j e ct Pu re Vi rt u a l Fu n ct Compile and run the program. The output should
io n s . 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
ab st ra ct class. class Employee and two derived classes Salaried
Understand how to create a and Hourly.
pu re vi rt u al function and The output for each of the two instance objects
understand the difference appears twice to demonstrate the use of sta t i c and
between a vi rt ua l function d yn a mi c binding.
and pu re vi rt u al function.
You will also be introduced
to sta t i c and d yn a mi c
bi nd i ng .
Figure 168
Step 2
Open ma in . cp 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 ob je ct
E mp lo yee .
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 sE mp lo yee of
class Sa la ri e d and initialises the data members via
the constructor.
The second statement creates an instance
h E mp l o ye e of class Hou rl y and initialises the data
members via the constructor.
Figure 170
Step 4
Examine the statements shown in Figure 171. The
statement sE mp l o ye e .p ri n t () is using the dot
member-selection operator “object.method()”.
This means the compiler can identify (knows
about) each object (sE mp lo yee and hE mp lo ye e )
at compile time and knows which p rin t and
e a rn i ng s functions to call. This is sta t i c b in d in g .
Figure 171
Step 5
Examine the statements shown in Figure 172.
Figure 172
In this statement we create a vector to hold
p oi n te rs of type E mp l o ye 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 al a ri ed Employees and Hou rl y paid Employees.
The addresses are stored in base class E mp lo yee
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
vi rt ua l Po i n te r .
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 rin t () function using
the base class (E mp l o ye e ) pointer and the arrow
notation (- > ). This calls the derived class p rin t ()
function.
Figure 175
Task 1 Step 1
Create a new project, call it Using the hierarchy shown in Figure 167 create an
Sh ap e s . abstract class S ha pe with no implementation.
Step 2
Create three derived classes, Pa ra l le l og ra m ,
Re cta n gl e and Tri an g le . 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 ecl i p se , o pe n t he Open A TM. cp p .
p ro j e ct St ud e nt A TM
Ab st ra ct B al an ce I nq u i ry Examine the statement:
Transaction * transactionPtr;
This statement creates a ba se class pointer
(t ra n sa ct i on P t r ) to the Tran sa ct io n class.
Transaction is an ab st ra ct 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 al a n ce In q ui ry , Dep o sit and Wi th d ra wa l. See
Figure 176.
Note the common behaviour for the derived classes
is run () .
Figure 176
Step 2
Examine the statement:
t ra n sa ct io n Pt r = cre at e Tra n sa ct io n (se le ct io n );
cre a te Tra n sa ct io n () is a p ri vat e ut i li t y fu n ct i on
and can only be accessed from within the class.
se le ct io n is the user input choice from the menu
(1-4). cre a te Tra n sa ct io n returns a pointer of type
determined by the user input (1-4).
Figure 177
Step 3
Examine the crea t e Tran sa cti 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 al a n ce In qu i ry , Wi t hd ra wa l or Dep o sit .
Case select option 3 (Dep o sit ) is not functional just
yet so there is a prompt to let the user know.
If the user inputs a 1, a Ba la n ceI n qu i ry object is
dynamically created and assigned to a base class
pointer t e mpP t r .
Similarly if the user inputs a 2, a Wi th d ra wa l
object is dynamically created and assigned to the
base class pointer te mp Pt 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 Dep o sit
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 UCS A TM .
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
first-class containers . Other containers are called adapters and near
containers . Pointer based arrays, string, bitsets and valarrays are near
containers, we will not be looking at those in this session.
Containers in the STL fall into two categories, sequence containers see Table
8, and associative containers see Table 9.
se q u en c e c on t a i n er s
vector
lists
deque
T ab l e 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. size().
size() 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 <algorithm> 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 begin() and end().
begin() returns an iterator pointing to the first element in the container and
end() 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, ++ it r
points to the second element and * it r refers to the element pointed at by it r .
Note that the iterator resulting from end() 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 nd () 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, ran do m a cce ss 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
A ll i t er a t o r s
Iterator operation
I n p u t i t e r a t o rs
*p dereference an iterator
p = p1 assign one operator to another
p == p1 compare iterators for equality
p != p1 compare iterators for inequality
O u t p u t i t e r a t o rs
*p dereference an iterator
p = p1 assign one operator to another
F or w ar d i t e r a t o rs forward iterators contain all the functionality of
both input iterators and output iterators
B i di r ec t i o n a l i t er a t o r s
Table 14
In the example below the so rt () algorithm is using two iterators pointing to the
start and end of the vector called myVe ct o r ;
sort (myVector.begin(),myVector.end();
Because so rt () algorithm uses random-access iterators to the initial and final
positions of the sequence to be sorted, so rt () can be used with the ve cto r and
d eq ue containers but not the li st container. Lists only support bidirectional
iterators.
However, li st containers have a member function so rt () that can be used to sort
list elements.
Table 13 shows the different iterators supported by each container.
Table 15 shows predefined iterator t ype de f s found in the class definitions of the
STL containers.
P r ed e f i n e d t y p e de f s f or i t er a t o r t y p es Di r ec t i o n o f ++ Ca p a bi l i t y
iterator forward read/write
const_iterator forward read
reverse_iterator backward read/write
const_reverse_iterator backward read
Table 15
Table 16 and Table 17 below show the member functions and algorithms available
to each container, ve cto r , li st and de qu e .
The STL algorithms can also be decoupled from the STL container classes. What
this means to us is that certain algorithms (re ve rse 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 re ve rse algorithm with the l i st container is because
re ve rse uses bidirectional iterators supported by the li st container.
V e c t o r M e m b e r F u nc t i o ns Li s t M e m b e r F u nc t i o n s
vector::assign vector::max_size list::assign list::pop_front
vector::at vector::operator = list::back list::push_back
vector::back vector::operator [ ] list::begin list::push_front
vector::begin vector::pop_back list::clear list::rbegin
vector::capacity vector::push_back list::empty list::remove
vector::clear vector::rbegin list::end list::remove_if
vector::empty vector::rend list::erase list::rend
vector::end vector::reserve list::front list::resize
vector::erase vector::resize list::get_allocator list::reverse
vector::front vector::size list::insert list::size
vector::get_allocator vector::swap list::max_size list::sort
vector::insert list::merge list::splice
list::operator = list::swap
list::pop_back list::unique
Table 16
D e qu e M e m b e r F u nc t i o n s
deque::assign deque::operator =
deque::at deque::operator [ ]
deque::back deque::pop_back
deque::begin deque::pop_front
deque::clear deque::push_back
deque::empty deque::push_front
deque::end deque::rbegin
deque::erase deque::rend
deque::front deque::resize
deque::get_allocato
r deque::size
deque::insert deque::swap
deque::max_size
Table 17
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 st rea m> header file. This allows the use of
o f st re 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 ou t Fil e is created.
ofstream outFile;
outFile.open("Numbers.txt", ofstream::out );
i o s: : ou t and o f st re a m: :o u t are modes the file will be opened in. In the above
cases o ut denotes writing to file with any existing data in the file being deleted.
Mode i o s: : ap p appends data to the file.
When data has been transferred to file the interface can be closed (or
disassociated) by calling member function cl o se , outFile.close(); Once
closed, the same file stream object can be used to open another file.
To read from a file the if st re 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 op en .
ifstream inFile;
inFile.open("Numbers.txt", ofstream::in );
After all data has been transferred the interface can be closed (or disassociated)
by calling member clo se . Once closed, the same file stream object may be used
to open another file.
The member function i s_op e n can be used to determine whether the stream
object is currently associated with a file.
The following program shows how to add each element of an array of integers to
file. The program then reads each record from file into another vector and the
contents output to screen
Task 1 Exercise 68
In eclipse, ope n the Open Fi le I O project and examine the code. Only
project Fi l eI O in the the parts that relate to writing to and reading from file
IO Ba si c I N_O UT are covered here.
folder and examine the
code to establish how to The <f st rea m> header file is included to allow the use
read and write files. of o f st re a m and if st re a m classes to create instance
objects to read and write to and from file.
Exercise 69
of st rea m o ut Fi l e ("Nu mb e rs. t xt ", i o s: : ou t );
The statement above creates an instance of of st rea m
called ou t Fil e . The ofstream constructor takes two
arguments, the name of the file and how the file should
be opened.
In this example o ut indicates any data in the file will be
overwritten. i o s: : ap 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.
Not e that it is unnecessary to write io s: :o u t so the line
could have been written of st rea m
ou t Cl ie n t Fi l e ( "cl i en t s.t xt ") ;
Exercise 70
if (ou t Cl i en t Fi le . fa i l ())
fa i l () is a member function that the of st rea m object
ou t Fil e inherits.
If for some reason the file cannot be opened for writing
an error message is given and the function exi 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
whi l e (cou n t < i nt S to re . si ze ()) uses a wh i le loop to
loop through vector i nt S to re .
Member function si ze () gets the number of elements
in the vector to control the while loop outputting each
element to file followed by the return character e nd l .
Step 1
ou t Fil e << i nt S to re .a t (co un t )<<e n d l ;
ou t Fil e is the object that points to the file
Nu mbe rs. t xt.
Each element in the i nt S to re vector is passed to file
together with the end of line character using stream
insertion operators <<.
ou t Fil e . clo se (); closes the file.
Step 2
Let’s see how to read from file.
if st re a m in Fi le ( "Nu mb e rs. t xt ", i o s:: i n );
The statement above creates an instance of if st re a m
called in Fi l e . The i f st rea m constructor takes two
arguments, the name of the file and how the file should
be opened, in this case we are reading in .
in Fi l e. cl ea r(); resets e of for input, though this is not
really necessary here as in Fi l e has just been created.
in Fi l e. see kg (0 ); positions pointer to beginning of
file, again as we’ve just created in Fi l e , it’s not strictly
necessary.
Step 3
If (i n Fi le . fa i l ())
fa i l () is a member function that the if st re a m object
in Fi 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 xit called and the program
terminates.
Step 4
whi l e (! in Fi l e. e of ())
{
i n Fil e >> r;
st o reS o rt .p u sh _b a ck(r);
}
The while loop reads the integers input stream object
in Fi l e while not meeting the end of file character.
Each integer is stored in variable r and then pushed
onto the vector st o reS o rt .
in Fi l e. cl o se (); closes the file.
Step 5
The statement st o reS o rt .e ra se (sto re S o rt. e nd ()- 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 nd l is to create an additional
record. See the statement below which was used
earlier in the program to pass vector elements to file.
ou t Fil e << i nt S to re .a t (co un t )<<e n d l ;
Step 6
so rt (st o re So rt . be g in (), st o re So rt . en d ()); so rt is an
algorithm that uses random access iterators.
The so rt () algorithm sorts the elements in the range
[ st o reS o rt .b e gi n (), st o reS o rt .e n d ()] into ascending
order with the elements being compared using a
default < (less than) operator.
Step 7
fo r (i n t i = 0; i < sto re So rt . si ze (); i ++)
ou tp u tL i ne (st o reS o rt [ i] );
The fo r loop is used to iterate through the vector
passing each element in turn to the function
ou tp u tL i ne where it is output.
A static counter in the function o ut pu t L in 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, myVe ct o r[1 0 ];
Vectors support ra nd o m acce ss it e rat o rs 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 csA nd I t s in the Open Ve csAn d It s and examine the code.
Ve cto rs a nd It e rat o rs
Only the parts that relate to vectors, iterators and
folder and examine the
algorithms are covered.
code to establish how to
read and write files. Have a look at the code shown in Figure 183. The
code shows the function prototype for template
function Ou t Pu t Ve cto rE l e men 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 con st an t
so any iterators we use must also be constant.
Figure 183
Exercise 74
In the statements do ub s.p u sh _b a ck(a +1 .3 ); and
in t s.p u sh _b a ck(a +1 ); we use the vector member
function pu sh _b a ck() .
pu sh _b a ck 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 ut P ut V e ct o rE le me n t s(in t s); passes
the vector i nt 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 co n Re vIt .
Notice that con st _re ve rse _i te ra to r is a f o rwa rd
on l y iterator, see Table 14.
This means, as the names suggest the iterator can only
move forwards through the container.
Importantly, f o rwa rd i te ra t o rs 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 re nd () .
The significance of this is explained in the next step.
Figure 185
Exercise 78
In Figure 186 the fo r loop condition is testing to see if
the iterator con Re vI T is not equal to iterator
co n Te mpI T .
It would seem intuitive to write this conditional
statement as co n Re vI T < con Re vI T. ren d ()
However, con Re vI T is a forward iterator and does
not support the < operator so we assigned the iterator
ren d () to con Te mp 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 co n sta n t
iterator that can read a const element in a vector.
Figure 187
Exercise 80
In Figure 188 the fo r loop condition is testing to see if
the iterator con I T is less than the iterator returned by
in Va l ue . en d ().
Not e that we can use the test condition operator <
(less than), as con I T is a random-a cce ss iterator.
Figure 188
Task 1
Modify the program to
read from file in t s.t xt all
the values into a vector
of integers. Show the
vector before and after
sorting.
Read in the values from
do ub s. t xt . 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, ma x_e l e men t and mi n _e l e men t .
Read the data from the
file do ub s. t xt into a ma x_e l e men t returns an iterator pointing to the
vector. largest element in a range and mi n _e le me nt returns
an iterator pointing to the smallest element in a range.
Establish the max,
minimum and mean The format for mi n _e le me nt 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
myI te ra to r ,
myI te ra to 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 go ri 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 med i an
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 ush _ba ck member function is
used to add values to the end of the list.
Li st containers also have member functions
pu sh _f ro n t and p op _f ron 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 t1 of
the first element in the list d ou b. b eg i n () .
in se rt () member function adds an element be fo re the
element pointed at by iterator i t1 .
In this example we are adding 69 .6 9 at the beginning
of the list.
Note: after in se rt () iterator i t1 is still pointing at the
same value in the list that was identified as
do ub .b e gi n () , i.e. now the second element.
Not e : this version of the in se rt () 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 so rt () 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 so rt () member function is used sort
the list d ou b s() .
The merge member function is then used to merge
do ub s with list d ou b , the merge is to list d ou b .
Not e that this will empty the second list do ub s .
Figure 197
Exercise 91
In Figure 198 we want to copy the contents of d ou b ()
list to the now empty list d ou b s() . To do this we use
the cop y() algorithm.
The co p y algorithm uses i np u t i te ra t o r and o ut pu t
it e ra to r that are supported by l i st containers
Not e : before using the cop y algorithm the list
do ub s() has to be resized using list member function
re si ze () to match the size and number of elements
that will copied into it.
Figure 198
Exercise 92
In Figure 199 the u ni qu 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 do ub with the content of do ub s .
Obviously both lists must contain elements of the
same type but list si ze s may differ.
After the call to the member function the elements in
do ub container are those which were in do ub s , and
the elements of do ub s are those which were in do ub .
Not e that an a lg o ri th m exists with the same name
swap , which has the same behaviour.
Figure 200
Exercise 94
In Figure 201 iterator i t1 is positioned at the start of
the list using function be gi n () .
STL class iterator ad van ce () advances the iterator
it 1 , twice to the third element of the d ou b list.
Iterator i t1 will be used with the sp l i ce () member
shown in Figure 202.
Figure 201
Exercise 95
Figure 202 member function sp l i ce () is used to move
elements from list to list.
Elements are moved from myL i st into the list
container d ou b at the specified position i t1 .
Not e : iterator it 1 has already been moved to the third
element position.
The element at location i t2 in myL i st , “10” is moved
from myL i st into list d ou b .
myL i st has one element less and do ub has one
element added at position it 1 .
Figure 202
Exercise 96
Figure 203 shows how to use the sp l i ce member
function with a different template. This function
template needs four parameters.
Pa ra me te r1 is the position in the container where the
elements of myL i st are inserted; do ub .b e gi n () .
Pa ra me te r2 is the list object myL i st containing the
same type of objects as d ou b container.
Pa ra me te rs3 & 4 are iterators specifying a range of
elements in myL i st . The elements in this range are
moved to d ou b. b eg i n () .
Notice that the range includes all the elements
between i t1 and myL i st . en d () the element pointed by
it 1 but not the one pointed by myL i st . en d () as this
points past the last element in the list.
Figure 203
Task 1 Exercise 97
Create a new project, call Create a li st and li st it e ra to r .
it Li st Fi n d A nd E ra se Load the file L i st Nu mb e rs. t xt to the l i st .
Exercise 98
Use the fi n d () STL algorithm (there is no member
function) to return an iterator to the position in the
list of a known number.
it = f in d (myL i st .b e gi n (), myL i st. en d (), a nI nt );
Exercise 99
Add a number of your choice together with the
returned iterator from fi n d to the in se rt 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 ve cto rs and d eq ue 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 so rt () algorithm,
elements are sorted into ascending order.
Class deque does not have a member function sort,
but we can make use of the so rt () alogorithm.
myDe qu e. b eg i n () and myDe qu e. e nd () 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 in se rt () member
function with de qu e .
The de qu 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 st
container.
Figure 208
Exercise 106
Figure 209 shows the deletion of a deque element
other than at the end of the container.
myDe qu e. b eg 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 li st .
Figure 209
Exercise 107
Examine the code in Figure 210. In this example we
are using the i n se rt function with a different number
of parameters.
The parameters here indicate where in the de qu e the
elements will be inserted (it 1 ) and the range of
elements to be inserted myVe c. be g in () to
myVe c. en d () .
Not e that the element pointed to by myVe c. en d () is
not copied.
Figure 210
Task 1
Modify the program in
Deq ue A nd I t s. d e v so
only the first two
elements in myV e c are
copied to the deque.
Figure 211
Exercise 110
In Figure 212 the t yp ed e f keyword creates an alias
called mu lt S et for a mu l t i se t container data type.
Th e ef fe ct of th i s st at e men t i s t o so rt the mu lt i set
from l o we st to hi gh e st .
Figure 212
Figure 213
It is useful to define types when it is possible that the
da ta t ype 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 le ss<i n t >
function object for less-than inequality comparison.
le ss has its operator () member defined such that it
returns t ru e if its f i rst argument compares lower than
the second one using operator < , and f al se otherwise.
The effect of "le ss " is to so rt the mu lt i set from
lo we st to h ig he st .
To sort from highest to lowest use "g re a te r " function
object.
Exercise 112
Figure 214 shows the co u nt () 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 in t Mu lt i se t .
Figure 214
Exercise 113
Figure 215 shows the creation of constant iterator
called re su l t .
The scope resolution operator : : is used to enable the
name of the member that follows the operator
(con st _i t e ra 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 id i re ct io na l .
Figure 215
Exercise 114
Figure 216 shows the use of the fi n d () member
function which returns a bidirectional iterator.
The function is used to search the container for an
element with a value of 15 and return the iterator to it
if found.
If the value is not found an iterator to mu lt i set : : en d ()
is returned. The e nd () 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 se rt member function
to extend the container by adding all of array a
elements.
a and a + SI ZE 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 lo we r_b ou nd returns an iterator
pointing to the first element in the container which
does not compare less than 24 (using the container's
comparison object, defined in t ype de f , in this case
le ss ).
A pointer is returned to a value that is either equal to
or greater than the key value, de re fe re n ce d here.
Figure 219
Exercise 118
Figure 220 shows up pe r_b ou n d member function
which returns an iterator pointing to the first element
in the container which compares greater than the ke y ,
24 (using the container's comparison object, le ss ).
Unlike l o we r_bo un 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 rea t e r .
If the iterator is passed the container last element its
equal to i nt Mu l t i se 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 ai rs utility
components. p represents a pair of con st _i t e ra t o rs ,
in this case mu l tS e t con st _i t e ra t o rs .
The pa i r class couples together a pair of values, which
may be of different types. The individual values are
accessed through the public members fi rst and
se co nd .
Figure 221
Exercise 120
Figure 222 shows the member function eq ua l _ra ng e
returning a pair of iterators, p. f i rst and p . se con d .
Member p .f i rst is an iterator to the lower bound of
the range with the same value as would be returned by
lo we r_b ou nd (ke y).
p. se co nd is an iterator to the upper bound of the
range with the same value as would be returned by
up pe r_b ou n d (ke y) .
So it’s another way to get lo we r_b ou nd and
up pe r_b ou n d values.
Figure 222
Exercise 121
The values pointed at by the returned iterators are
output using the d e re f e ren ce 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 yp ed e f mu l t map called cCa rd No .
Figure 226
Exercise 126
In Figure 227 two va lu e _t yp e objects are inserted in
cCa rd No multimap. The values entered are integers
and doubles for the ke y & va l ue of the first two
elements.
va l ue _t ype is a synonym for t ype as defined in the
t yp ed e f for multimap at the start of the program, in
this case the ke y is type i nt and the va l ue type
do ub l e .
Figure 227
Exercise 127
Figure 228 shows the use of a con st _i t e ra t o r named
it e r to run through cCa rd No multimap using pointer
notation to access members f i rst and se co n d .
The iterator defined by mu lt i ma p points to objects of
va l ue _t ype which are of type pa i r <con st Ke y,
Typ e > .
The value of the K e y is available through the first
member pair and the value of Typ e of the mapped
element is available through the second member of
the pair.
To dereference an iterator it e r pointing to an element
in a mu l t i map we use the arrow - > operator.
To access the value of the key for the element, use it e r
-> f i rst which is equivalent to (*i te r). f i rst .
To access the value of the mapped data for the
element use it e r -> se co n d which is equivalent to
(*I te r). se con d .
Figure 228
Figure 230
Exercise 129
Use the mu lt i ma p cou n t () member function in a fo 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 fo r loop add code similar to Figure
232.
The function eq ua l _ra ng e returns a pa i r , where its
member p ai r: : f i rst is an iterator to the lower bound of
the range (ex the first of many 1's).
pa i r: : se con d is an iterator to the upper bound of the
range (ex the last of many 1's).
in d to ta l is the sum of the mapped va l ue 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
cli e nt sDe b t. t xt .
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
I n cre me n t in g a va ri ab l e .
mo n th = mon t h + 1 ; adds the value one to the variable mon t h . This can be
written as mon t h ++;
De cre me nt i ng a va ria b le .
mo n th = mon t h - 1 ; deducts the value one from the variable mon t h . This can be
written as mon t h --;
To add 2 to a variable to ta l :
t ot a l = t ot a l + 2 ; or t ot a l +=2 ;
To subtract 2 from to ta l :
t ot a l = t ot a l - 2 ; or t ot a l - =2;
To multiply t ot a l by 2 :
t ot a l = t ot a l * 2; or t ot 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 le sco 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 bl o ck sco pe . 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 co n st
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 me mb e r fu n ct i on 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 xa mp l e : strcpy(a1, a2); copy the contents of array a2 into array a1.
No te : 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 <cst ri ng > .
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)