An Introduction to C++ and Object Oriented Programming

Abstract
The aim of the notes is to provide an introduction to the C++ programming language and object oriented programming. It is assumed that you know one programming language moderately well.

Author: Ian D Chivers Email: ian.chivers@kcl.ac.uk Version: 6.1 Date: August 1999 © Ian D Chivers. Permission to copy all or part of this work is granted, provided that the copies are not made or distributed for resale (except a nominal copy fee may be charged), and provided that the Author, Copyright, & No Warranty sections are retained verbatim and are displayed conspicuously. If anyone needs other permissions that aren't covered by the above, please contact the author. No Warranty: this work is provided on an as is basis. The author provides no warranty whatsoever, either express or implied, regarding the work, including warranties with respect to its merchantability or fitness for any particular purpose. All comments welcome.

Contents
Table of Contents

3

1 Overview...............................................................................................................14
1.1 1.2 1.3 1.4
1.4.1

Aims............................................................................................................................14 Assumptions ...............................................................................................................14 Additional Material and Recommended Sources ......................................................14 Compilers and Standards............................................................................................15
Contents of the standard...................................................................................................16

1.5 1.6 1.7 1.8 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11 2.12 2.13 2.14 2.15
2.15.1 2.15.2 2.15.3 2.15.4 2.15.5 2.15.6 2.15.7 2.15.8 2.15.9 2.15.10 2.15.11 2.15.12 2.15.13 2.15.14

Old and New...............................................................................................................17 Coda............................................................................................................................17 Course Details ............................................................................................................18 Problems .....................................................................................................................18 Fortran 66, 1966 .........................................................................................................20 Pascal, 1975, ANSI & BSI 1982, ISO 1983, Extended Pascal 1991?......................20 Fortran 77, 1978 .........................................................................................................21 C, K&R 1978, Standard 1989. ...................................................................................21 Modula 2, 1982, Standard 1996? ...............................................................................21 Ada, ISO 8652: 1987 .................................................................................................21 C++, 1986, Standard November 1997 .......................................................................21 Oberon 2, Late 1980's, early 1990's...........................................................................22 Fortran 90, 1991. ........................................................................................................22 Eiffel, 1988 .................................................................................................................22 Ada, ISO 8652: 1995 .................................................................................................22 Java .............................................................................................................................23 Visual Basic................................................................................................................23 Language Comparison................................................................................................23 Language Features......................................................................................................25
Independent Compilation .................................................................................................25 Separate Compilation .......................................................................................................25 Concrete Data Types ........................................................................................................25 Abstract Data Types .........................................................................................................25 Dynamic arrays.................................................................................................................25 Numeric and General Polymorphism...............................................................................25 Modules ...........................................................................................................................26 Pointers and References ...................................................................................................26 Procedure Variables .........................................................................................................26 Inheritance ........................................................................................................................26 Dynamic Binding .............................................................................................................26 Operator Overloading.......................................................................................................26 Threads/Multitasking........................................................................................................26 Exception Handling..........................................................................................................27

2 An Introduction to Programming Languages and Object Oriented Programming ...................................................................................................................20

2.16
2.16.1 2.16.2 2.16.3 2.16.4

Some Important Milestones in Program Language Development ............................27
Structured Programming ..................................................................................................27 Stepwise Refinement........................................................................................................27 Data Structuring, Concrete vs Abstract Data Types........................................................27 Information Hiding – Modules ........................................................................................27

2.17 2.18
2.18.1 2.18.2

Terminology of Object Oriented Programming.........................................................27 Parallel Developments................................................................................................27
Parallel Fortran – Fortran 95, Fortran 2000, SMP, MPI, HPF .......................................28 Parallel C++......................................................................................................................28

2.19 2.20
2.20.1 2.20.2 2.20.3 2.20.4 2.20.5 2.20.6 2.20.7

Object Oriented Programming ...................................................................................28 Object Oriented Languages ........................................................................................29
Simula – 1967 ..................................................................................................................29 Smalltalk – 1978 ..............................................................................................................29 C++ ...................................................................................................................................29 Eiffel .................................................................................................................................29 Oberon 2 ...........................................................................................................................29 Ada 95 ..............................................................................................................................30 Java ...................................................................................................................................30

2.21

Other Languages.........................................................................................................31

4
2.21.1 2.21.2

Contents
Fortran 90 .........................................................................................................................31 Modula 2...........................................................................................................................31

2.22
2.22.1 2.22.2 2.22.3

The OO Approach ......................................................................................................31
Meyer's Approach ............................................................................................................31 Rumbaugh et al ................................................................................................................31 Practical Steps ..................................................................................................................32

2.23 2.24
2.24.1 2.24.2 2.24.3 2.24.3.1 2.24.3.2

Simple Example..........................................................................................................32 Other Developments...................................................................................................33
Development Environments .............................................................................................33 Graphical Development Tools .........................................................................................34 Software Components ......................................................................................................34 COM, OLE, ActiveX.................................................................................................34 JavaBeans...................................................................................................................35

2.25 2.26 2.27 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8
3.8.1 3.8.2 3.8.3 3.8.4

Coda............................................................................................................................35 Bibliography ...............................................................................................................36 Problems .....................................................................................................................41 Hello World – Old C style .........................................................................................44 Hello World – New standard C++ style ....................................................................44 Simple text i/o using C style arrays of char ..............................................................45 Simple text i/o using C++ style strings .....................................................................46 Simple numeric i/o .....................................................................................................46 Some C++ Rules and Terminology ...........................................................................47 Good Programming Guidelines..................................................................................48 C++ for C Programmers.............................................................................................48
Macros ..............................................................................................................................48 Malloc...............................................................................................................................48 Pointers .............................................................................................................................48 Arrays and C style strings................................................................................................48

3 An Introduction to C++ ......................................................................................44

3.9 3.10 3.11
3.11.1 3.11.2 3.11.3

C++ Character Set ......................................................................................................48 Summary.....................................................................................................................49 Key Concepts..............................................................................................................49
Basic structure of a C++ program ...................................................................................49 Indentation ........................................................................................................................49 Data Types........................................................................................................................49

3.12 3.13 4.1 4.2
4.2.1

Bibliography ...............................................................................................................50 Problems .....................................................................................................................50 Basic numeric types ...................................................................................................54 Integer Numeric Type ................................................................................................54
Variations on a theme - signed, unsigned........................................................................54

4 Arithmetic and Expressions in C++ ..................................................................54

4.3 4.4 4.5 4.6 4.7 4.8
4.8.1 4.8.2 4.8.3 4.8.4 4.8.4.1 4.8.4.2 4.8.4.3 4.8.4.4 4.8.4.5 4.8.4.6 4.8.4.7 4.8.4.8 4.8.4.9 4.8.4.10 4.8.4.11

Real Numeric Type ....................................................................................................55 Numeric Type Conversion Rules ...............................................................................55 Complex?....................................................................................................................56 const............................................................................................................................56 Character Data as a form of Integer Data..................................................................56 Operators and Expression Evaluation ........................................................................57
Expression Evaluation......................................................................................................57 Sequence Points................................................................................................................57 Lvalue and Rvalue............................................................................................................57 Operators, Precedence and Associativity.........................................................................57 :: [scope resolution] class_name :: member..............................................................59 :: [global] :: name ......................................................................................................59 . [member selection] object.member .........................................................................59 -> [member selection] pointer -> member ................................................................59 [] [subscripting] pointer [expr] ..................................................................................59 () [function call] expr (expr_list)...............................................................................59 () [value construction] type(expr_list).......................................................................59 ++ [post increment] lvalue ++...................................................................................59 — [post decrement] lvalue — ...................................................................................59 sizeof [size of object] sizeof expr .............................................................................59 sizeof [size of type] sizeof (type)..............................................................................59

...............................4.....................16 4.......................................* [member selection] object....................................................................................60 ->* [member selection] pointer -> * pointer_to_member ......................................................................1...........61 | [bitwise inclusive OR] expr | expr .............61 >= [greater than or equal] expr >= expr ..............48 4...62 |= [inclusive OR and assign] lvalue |= expr.....61 ?: [conditional expression] expr ? expr : expr ..31 4...........................................................................................................................4.........4 4...................1.........................................4.....................s2) .........................60 & [address of] & expr....55 4............... [comma] expr ....4........61 && [logical AND] expr && expr..............8.................19 4...................................1 5.............................60 () [cast] (type) expr........4........................1....................................4.....62 throw [throw exception] throw expr......................................................................27 4............................8...........* pointer_to_member.............8......................................................61 <= [less than or equal] expr <= expr ........................11................61 << [shift left] expr << expr .4.........................................................................8.........32 4.....4.........4................................1..........4.........................................................................expr....56 4..............62 Summary........................11.........50 4...............3 Problems ...............65 4........................62 += [add and assign] lvalue += expr .....4...............68 Example 2 ..8....................18 4.........................60 delete [destroy] delete pointer ................................................65 Complex – supported via <complex> ..............................1 4......57 5 ++ [pre increment] ++ lvalue ...........................................................................................................8............8....................11...........8..62 4...................................11..........................36 4.......34 4...................3 4.....8............11................8...................41 4.............38 4.........................40 4........44 4...........................60 + [unary plus] + expr..............62 ..60 ~ [complement] ~ expr .........8.......................................20 4............8................................[minus] expr ........................................61 || [logical inclusive OR] expr || expr ...........8......................1..1....................................................................8............53 4....68 strcpy(s1.........23 4................................................8........65 Constants – use the const attribute ..12 4..4.............8............................65 Real ............................4..........4.............1................................22 4............................65 Expressions – the order of expression evaluation is often undefined..................60 * [dereference] * expr...................................................................................................................................28 4.................................................................4............................62 <<= [shift left and assign] lvalue <<= expr .......................61 & [bitwise AND] expr & expr .........................................8.......................................................................................4.............................8............8......................8.............1 5...................................11...............49 4.4.1......................12 5............................4.......4............4.............................4.14 4......13 4........4....................................................................................................54 4............................................... expr .26 4.1...............................................8..................................8...............4............................................11 4.......4.........................................8......................2 4.8..............................65 Integer .......65 Operators – 45 but effectively 57 with variants ..............4.............................8..........51 4.8...............8..........................65 Character Data or Strings ..........8............expr.................60 new [create] new type.........................11.........................24 4........................................37 4.....................................4...............................4................8............................4...30 4....4.........11............62 = [conventional assignment] lvalue = expr ..................................64 Key Concepts................68 Example 1 ................61 ^ [bitwise exclusive OR] expr ^ expr.................................8......4.............46 4.....65 Numeric Data Types ............................8...................43 4...39 4........62 /= [divide and assign] lvalue /= expr ....Contents 4.........................4.4...........................1 4.........8.........4..........................2 5.3 4..............................2 4....47 4...........8..........29 4..........................69 5 Strings and other Data Types ...............42 4........61 > [greater than] expr > expr .........17 4............................35 4.......................................61 < [less than] expr < expr .....61 + [plus] expr + expr..........1..............................60 delete[] [destroy array] delete [] pointer .................4........25 4.................8....62 >>= [shift right and assign] lvalue >>= expr............8..................61 != [not equal] expr != expr.............61 ..4.................................4.....4....................8............................60 % [modulo or remainder] expr % expr ...........................60 .........................62 &= [AND and assign] lvalue &= expr........62 %= [modulo and assign] lvalue %= expr...............................................................4..............................................60 ! [not] ! expr ........................4.......................................65 Character Data as Numeric Data..........................52 4..............4.................................................45 4.........4...........................................68 ...4.........................................15 4...................[unary minus] ........................8..................................8....................60 ...........................4..........................4..8...........8..............4 Expression Examples..................10 4.........................61 >> [shift right] expr >> expr ...4..........62 *= [multiply and assign] lvalue *= expr ...............................60 * [multiply] expr * expr .60 / [divide] expr / expt ................................................61 == [equal] expr == expr .........9 4....................................1.............................................1 5...............................................62 ^= [exclusive OR and assign] lvalue ^= expr ....................................8...........................59 — [pre decrement] — lvalue....................68 C Style strings ......................................8...............................4....................62 -= [subtract and assign] lvalue -= expr ..8.............................................8.8.....21 4........................................33 4...............8........................................................................

................................................1......10 5.....................1.....................................................1..........................................................74 Key Concepts............................................1................1 6.....1........................................................2..........................2................................................7 Problems .......4 5....10....................82 Example 3 – subscript checking with try/catch ......83 6..................................................................10............................................................................... Vectors and Valarrays in C++...................................69 strcmp(s1..............................3 Boolean or Logical Data ........2.....................81 6 Arrays.1......................74 Memory .........................5 6........................................78 One d array – People's Weights.............................................................................71 Reference Variables......................4 6..................10..................................................................................3 Contents strcat(s1...1...........73 Void ..................................2..1......2.................s2) ..................................................................................................................85 valarray.................................................................................................................1........................................................69 character access.................................................................5 5....................................................................................1.....................................2 5........11 6.......................................10..................................1........................................1.........2.............3 5...........................5 5..........................................................6 5............................70 concatenation ...............................4 5...........................81 Whole Array Manipulation .............................7 5....................2............................................................................................................3 5.............1..............................72 Type Conversion .......................6 5....................1 6............6 5..1..........1........7 5......................2.................................74 Seqence of characters as a string....................74 Enumerated Types .......................70 length........................75 Old C Style arrays ..............2 6...............................9 5.......................2............6 6......3 6.......1.................................6 6...........79 Simple physics – voltage example..85 array .........................6 5.............3 6.........................7 5..............................................8 5........3 Array Element Ordering in C++ ............................................................................2...........................................70 removal..............................1......1.............1....................................71 5..................................8 5............2 5............70 Example 3 ...............................74 Data Types...........74 Sequence of characters as an array of char.........................14 5.........................................................74 Type Conversion.............84 Example 1.........................................2...............................................1.....................85 Key Concepts...................................................................80 Time Zone Example ...80 Array Initialisation .............................................................2...................4 5...........7 5................10 5...........................................................................................................12 5...................................69 strlen(s).......1........................................................................................................................1.......70 insertion.......74 Reference Variable .................................71 Enumeration Types..................................................................................................................................2 5.........1...............................................2......................................1..........74 Scope ..........1 Valarrays............3 6....................................9 5........79 Two d Array – latitude and longitude ...................................................................................................2.......................................................2 6............c)..........1........................................................................................69 assignment........................2 5.....................................................................................................................70 constructors .....71 Guidelines for use ................................83 Example 4 – whole array assignment ..74 Logical or boolean ................................................................................................10.......2 6.....................5 5........................70 resize ..................4 Vectors.....................................................................................................5 5.......1..................1 5....6........................................1...............................................................................................................................................2............................86 ........................................................................................................................13 5...................................................85 Data Types.............................1.............................................................................................................6..............................................................................................10.............................1 5.............................1.......3..................................................................................................................................74 Memory and C++ .......1.....................1...2 6......6........................................70 replacement ..................2.............................................................................................1............1................................1 6.70 i/o ..........................................................10......................................1....................................................2 5.....................................................................................................1................10...............................................................................................................73 Scope..78 6.............................................70 search .............................................................................................................1........................................................85 Summary...............................1......1...........74 5..................4 5..........1 6................74 Void..74 Summary...........................1.....69 C++ Style strings – <string>..................6 5..............3 5.......................85 vector............................................10..............................................2...........1 5........................................................6.10....................................................................................................69 comparison ............84 6...70 iterators................................................4 6......5 6.....78 One d example – Monthly Rainfall ......................................................................................1.11 5.....s2) ...............................81 Example 1.................1......69 strchr(s......2...................1 6..............81 Example 2 – subscript checking ................................

..........101 arrays and pointers ........................................................................................................93 do statement while expression............. vector as argument .............................................................................................................6.....................................................88 if (expression) statement ...........................4.............12....7 7...................2 9........................8 7......................................88 7................... expression 2) statement .....2 for (init-statement..........................................12................4..............90 7.................1......................................................2.......................4...........12........................12..........105 One d array as argument and one function.....................101 * – pointer to ....................................1 7.......................93 the switch statement.............................93 A block of statements – { ...6.2 if (expression) statement..6 7...................................100 Summary..............................................................................2 8....93 logical expressions .................89 Example 2....90 7.......101 8 Pointers ..................................3 7.........6 User Defined Functions...6........................................12...........................107 Passing 2d dynamic arrays as arguments ................................................................................................................................................................................................................................92 Key Concepts..............12 7.....................5 8.....2........................12.....................................................93 the if expression statement else statement ....................2 9...................................104 Trigonometric function usage ................86 6......2............................................7 7.............12......93 break statement ....................................................4 8....................2..................................................................................................................................1.......................93 7.....................89 7.....................88 7 Control Structures.................9 break..7...................................6 7..................9...........................104 Passing arguments of numeric type to standard maths functions ...............1 while (expression) statement ........................................................................................................3 Problems .......1 7...........1..4...............................................................93 continue statement ....................................................12.....................................3 9......................................6.............................93 Bibliography ....................................................92 Summary............................................12......................................90 Example 1............................................................ .....1 7..............................................1 8........................93 Control Statements .........91 Example 2.........105 3 functions..101 Key Concepts....................................................................................8.....................................................................................88 Boolean .......................................................................4....4....2 8.88 Example 2..................................5 9........................................................................................................................1 7..................... continue...................................... else statement..............................4...................4 7..............................90 Example 1.......................................................................................................................2 Problems .1.......................................................................92 7............11 7................................................................expression 1...4 7 Associated control structure – for loop ..........................105 9 Functions .....................12........................................................1 7.......1 do statement while (expression).................1 9...................109 .................................7 9.....................................................93 logical and relational operators ......2 7..................................................................93 goto statement ..........................108 Passing functions as arguments to other functions and procedure variables........................................101 Predefined Functions ..... goto statements ...Contents 6....................................................................................................99 Example 4: Indiscriminate Pointer Usage.............93 while expression statement ........................101 & – address of ....6.........................................4 9..................................88 Example 1.......................95 Example 1: Basic Pointer Usage.................98 8....98 Example 2: Arrays and Pointers .............................99 Example 3: Pointers and Sentinels........................................................................................4......5 7........................................................................93 the for () statement ......................................3 7..........................................................................................................................................86 Compound Statement or Block ...............7 7.....................................93 the if expression statement .............................................................5 7......12............................4..................4 7...8 7............89 Example 1.................................................................} .......................................................................................................2 9........4.........................................4...................5.............................................88 Expression................................................................................13 7.....1 9.......................................................................3 Problems ........................104 Functions in <maths....2 7........................3 7..............................................................................................6 8..........................................106 Using 2d arrays as arguments ............................................2 7...............................................105 One function........................................................................89 7.........................10 7..............................................................................................................89 Example 1.........................91 Example 1........1 switch (expression) statement .........12.....................................3 8..........................................................9.....................................12............................4 7.............................................................................14 8......................104 9........................................1 9..1 8.................................2..h>................................9 7..........................................................1 7...............................................2........................... one d array as argument.........5..........................

8
9.3
9.3.1 9.3.2 9.3.3

Contents
Function Arguments .................................................................................................111
Swapping arguments – passing by address....................................................................111 Swapping arguments – passing by reference.................................................................111 Mayhem ..........................................................................................................................112

9.4 9.5 9.6
9.6.1 9.6.2 9.6.3 9.6.4 9.6.4.1 9.6.4.2 9.6.4.3 9.6.4.4

C++ Standard Functions...........................................................................................112 Summary...................................................................................................................113 Key Concepts............................................................................................................113
Predefined functions.......................................................................................................113 User Defined functions ..................................................................................................113 Basic syntax....................................................................................................................113 Parameter Passing...........................................................................................................113 Pass by value – copy made .....................................................................................113 Array as parameter – base address used .................................................................113 Pass by reference .....................................................................................................114 Pass by const reference............................................................................................114

9.7 10.1
10.1.1 10.1.2 10.1.3 10.1.4 10.1.5

Problems ...................................................................................................................114 Concrete Data Types ................................................................................................116
Dates ...............................................................................................................................116 Addresses........................................................................................................................117 Nested Data Types .........................................................................................................118 Reading user input using a singly linked list ................................................................119 Reading user input using C++ style strings...................................................................120

10 Classes – User Defined Data Types .................................................................116

10.2
10.2.1 10.2.2

Abstract Data Types .................................................................................................120
Dates ...............................................................................................................................120 Addresses........................................................................................................................122

10.3
10.3.1 10.3.2 10.3.3

Sphere class ..............................................................................................................124
translate_with_copy_sphere ...........................................................................................127 translate_by_reference_sphere .......................................................................................127 translate_by_pointer_sphere...........................................................................................127

10.4
10.4.1 10.4.2 10.4.3 10.4.4 10.4.5 10.4.6 10.4.7 10.4.8

Constructors and Destructors ...................................................................................128
Constructor/Destructor Example 1.................................................................................128 Constructor/Destructor Example 2.................................................................................129 Constructor/Destructor Example 3.................................................................................131 Constructor/Destructor Example 4.................................................................................132 Constructor/Destructor Example 5.................................................................................133 Constructor/Destructor Example 6.................................................................................136 Constructor/Destructor Recommendations ....................................................................138 Memory Allocation and Deallocation – Leakage and Garbage Collection .................138

10.5 10.6 10.7
10.7.1 10.7.1.1 10.7.1.2 10.7.2 10.7.2.1 10.7.2.2 10.7.3 10.7.3.1 10.7.3.2 10.7.3.3 10.7.3.4 10.7.4

The C++ object Model – taken from the standard ..................................................138 Summary...................................................................................................................139 Key Concepts............................................................................................................139
Concrete data types ........................................................................................................139 Data public...............................................................................................................139 Functions public.......................................................................................................139 Abstract data types .........................................................................................................139 Data Private..............................................................................................................139 Functions public.......................................................................................................139 Constructors and Destructors .........................................................................................139 Simple constructor ...................................................................................................139 Copy constructor......................................................................................................139 Overload assignment operator .................................................................................139 Destructor.................................................................................................................139 Basic Class Syntax .........................................................................................................139

10.8 10.9 11.1 11.2 11.3 11.4 11.5

Problems ...................................................................................................................139 Bibliography .............................................................................................................140 Example 1 – Simple minimum ................................................................................142 Example 2 – Hoare's Quicksort ...............................................................................143 Other Issues ..............................................................................................................144 Summary...................................................................................................................144 Key Concepts............................................................................................................144

11 Templates............................................................................................................142

Contents
11.5.1

9

Basic Syntax Example....................................................................................................144

11.6 12.1
12.1.1 12.1.2 12.1.3 12.1.4 12.1.5 12.1.6

Problems ...................................................................................................................145 Operator Overloading...............................................................................................148
Unary and Binary Operators ..........................................................................................148 Operator Overloading 1: + , - , = ...............................................................................149 Operator Overloading 2: [].............................................................................................153 Operator Overloading 3: ().............................................................................................153 Operator Overloading 4: << and >>.............................................................................154 Guidelines for Operator Overloading ............................................................................155

12 Operator and Function Overloading...............................................................148

12.2
12.2.1 12.2.2 12.2.3 12.2.4 12.2.5 12.2.6

Function Overloading...............................................................................................156
Overload Resolution.......................................................................................................156 Exact Matching...............................................................................................................156 Matching through promotion .........................................................................................158 Matching through Standard Conversion ........................................................................158 Matching through User Defined Conversion.................................................................159 Guidelines for Function Overloading ............................................................................160

12.3
12.3.1 12.3.1.1 12.3.2 12.3.2.1 12.3.2.2 12.3.2.3

Key Concepts............................................................................................................160
Function Overloading.....................................................................................................160 Functions distinguished by signature ......................................................................160 Operator Overloading.....................................................................................................160 Unary operators........................................................................................................160 Binary operators.......................................................................................................160 Commutivity ............................................................................................................160

12.4 13.1 13.2 13.3 13.4
13.4.1 13.4.2 13.4.3 13.4.4 13.4.5

Problems ...................................................................................................................160 Virtual Function Example 1 .....................................................................................162 Virtual Function Example 2 .....................................................................................164 Summary...................................................................................................................166 Key Concepts............................................................................................................167
Virtual function ..............................................................................................................167 Pure Virtual Function.....................................................................................................167 Private.............................................................................................................................167 Protected .........................................................................................................................167 Public ..............................................................................................................................167

13 Virtual Functions and Abstract Data Types ..................................................162

13.5 14.1
14.1.1 14.1.1.1 14.1.1.2

Problems ...................................................................................................................167 Range Checked Array ..............................................................................................170
Notes...............................................................................................................................172 Class array................................................................................................................172 Class checked_array ................................................................................................172

14 Complete OO Example .....................................................................................170

14.2 14.3 14.4 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9
15.9.1 15.9.2 15.9.3 15.9.4 15.9.5 15.9.6 15.9.7 15.9.7.1

Summary...................................................................................................................173 Where do I go next?.................................................................................................173 Problems ...................................................................................................................173 Numeric i/o: width and precision.............................................................................176 Numeric i/o: setting justification..............................................................................176 Numeric i/o: scientific notation................................................................................176 Numeric i/o: alternate number bases, octal and hexadecimal .................................177 File i/o: picking up the names from the command line ..........................................177 File i/o: hard coded file names in constructors .......................................................178 File i/o: strings passed as arguments to constructors ..............................................178 Summary...................................................................................................................178 Key Concepts............................................................................................................179
Setting the width ............................................................................................................179 Setting the precision.......................................................................................................179 Justification.....................................................................................................................179 Reading from files..........................................................................................................179 Writing to files ...............................................................................................................179 Picking up files from the command line .......................................................................179 Alternate number bases for numeric output ..................................................................179 octal..........................................................................................................................179

15 Files and i/o ........................................................................................................176

10
15.9.7.2 15.9.7.3

Contents
decimal .....................................................................................................................179 hexadecimal .............................................................................................................179

15.10 Problems ...................................................................................................................179

16 Errors and Exception Handling.......................................................................182
16.1 16.2 16.3 16.4 16.5 16.6 16.7 16.8 16.9
16.9.1

Linked List – Pascal .................................................................................................182 Linked List – Fortran 90 ..........................................................................................183 Linked List – C++, old C syntax .............................................................................183 Discussion.................................................................................................................185 Example 1 – Basic Syntax .......................................................................................185 Example 2 – Exception raised in a function............................................................185 Example 3 – Function with Exception Specification ..............................................186 Example 5 – Exceptions and constructors and destructors. ....................................188 Key Concepts............................................................................................................188
Basic Syntax ...................................................................................................................188

16.10 Problems ...................................................................................................................188

17 The Standard Template Library .....................................................................190
17.1
17.1.1

Library Organisation ................................................................................................190
Some basic terminology.................................................................................................190

17.2
17.2.1 17.2.2 17.2.3 17.2.4 17.2.5 17.2.6 17.2.7

Containers .................................................................................................................190
vector ..............................................................................................................................190 list ...................................................................................................................................191 queue...............................................................................................................................191 stack ................................................................................................................................191 deque...............................................................................................................................192 map, multimap................................................................................................................192 set, bitset, multiset..........................................................................................................192

17.3 17.4 17.5 17.6
17.6.1 17.6.2 17.6.3 17.6.4 17.6.5 17.6.6 17.6.7

Iterators .....................................................................................................................192 Miscellaneous Operations ........................................................................................192 Constructors..............................................................................................................193 Algorithms ................................................................................................................193
Non modifying sequence operations..............................................................................193 Modifying sequence operations .....................................................................................193 Sorted sequences ............................................................................................................194 Set algorithms.................................................................................................................194 Heap operations..............................................................................................................195 Minimum and maximum................................................................................................195 Permutations ...................................................................................................................195

17.7 17.8
17.8.1 17.8.2 17.8.3

Strings .......................................................................................................................195 Numerics...................................................................................................................195
complex ..........................................................................................................................196 valarray ...........................................................................................................................196 numeric ...........................................................................................................................196

17.9 17.10 17.11 17.12 18.1 18.2 18.3
18.3.0.1 18.3.0.2 18.3.0.3 18.3.0.4 18.3.0.5 18.3.0.6 18.3.0.7 18.3.0.8 18.3.0.9 18.3.1 18.3.2

Complete list of C++ template classes ....................................................................197 Useful Sources..........................................................................................................197 Summary...................................................................................................................197 Problems ...................................................................................................................197 C++ as a Programming Language ...........................................................................200 The Standard.............................................................................................................200 C++ Standard Definitions.........................................................................................201
argument...................................................................................................................201 dynamic type............................................................................................................201 implementation defined behaviour ..........................................................................201 implementation limits ..............................................................................................201 multibyte character ..................................................................................................201 parameter..................................................................................................................201 signature ...................................................................................................................201 static type .................................................................................................................201 undefined behaviour ................................................................................................201 C++ Implementation Options: Free vs Hosted..............................................................202 The C++ Memory Model, taken from the standard ......................................................202

18 Miscellanea .........................................................................................................200

......................................202 ............................................................Contents 18....................4 11 Coda......

part II Aims The aims of the chapter are to provide a background to the organisation of the course. . let's kill all the language lawyers.' Henry VI.1 Overview 'The first thing we do.

Reference text. Springer Verlag. Fortran 90. This has not been officially ratified yet. The list is not exhaustive and your mileage will vary. 1. knows about the benefits of structured programming.uk . Also links to other sites.ac. write examples to test out my understanding. read the FAQ's.uk/kis/cc/fortran There is a lot of material here. Stroustrup. The designer of the language.kcl.2 Assumptions has a working knowledge of programming with one of Fortran 77.chivers@kcl.Chapter 1 1 Overview 1. The following are some of the sources I recommend. There is little coverage of the Standard Template Library. Visit the program language web pages on the college web server. Does not address all aspects of standard C++. An Introduction to Object-Oriented Programming in C++ with Applications in Computer Graphics. Complete example of ray tracing as a case study. The C++ Programming Language. knows about the data structuring facilities in one of the above languages. To get a reasonable working knowledge of some of the concepts in C++ I've found that I've had to:– read a variety of books. Comprehensive coverage.3 Additional Material and Recommended Sources The course material is not complete. C Pascal or Modula 2.1 Aims Overview 14 The aim of the course is to provide an introduction to the C++ language and object oriented programming. and as with many programming languages it is essential to get a feel for the language by someone who © Ian D Chivers email: ian. It is assumed that the reader:– 1.ac. consult the standard. The following are some sources I've found useful. This is the language as defined in the November 1997 standard document. as they won't address standard C++ in any real way. Note that there is no coverage of windows based programming. Addison Wesley. Introductory text. It is useful to make the following distinctions:– introductory texts on C++ reference texts on C++ good programming practice in C++ introductions to object oriented programming Don't bother at all with older texts. Seed. knows about the advantages of strongly typed languages. but there are not likely to be any major changes. Url is:– http://www.

Leave until one has a reasonable experience of C++. I'd get hold of these as they represent a very low cost source. Some of the examples given in the course may well not compile with your C++ compiler. The body of the standard is some 620 pages. Again a must. 1. C. The standard. numerics. Budd. About 30 uk pounds.ac. One of the original C team.4 Compilers and Standards I've adhered to standard C++ in this course and notes. It contains roughly 5 times as much material as the on-line version. Don't bother with any edition other than the third. I quite like it but someone has pointed out that it is aimed at so called language lawyers. The standard was finally published in November 1997. templates. but also look at some of the others. I would expect problems in the following areas:– namespaces. A lot of why questions are answered here. The chapters on design and development and design of libraries are essential reading if you are going to be involved in larger scale projects. cmath and cstdlib. If you want a highly technical coverage of the language then this is it. Data Structures in C++ using the Standard Template Library. The C++ home page for the course contains a link to it. The compilers in use currently will not be 100% standard conforming. If you are going to use C++ seriously then you must get hold of this book. but who likes to be wrong! Kernighan.uk © Ian D Chivers . valarray.chivers@kcl. History. This is a published book version of the on-line FAQs. HOPL.15 Overview Chapter 1 has had a major influence on what the language is today. numeric support: complex. the string data type with strings as objects. exception handling. Cline and Lomow. The on-line FAQs on C++ also contain much useful information. HOPL. C++. I would look at the various comp. newsgroups too. With the benefit of hindsight. I would imagine that when the standard is finalised the electronic copy will be removed.lang. This is a massive improvement over the other two editions. Stroustrup. This is currently available electronically on the net. Thoughts on the development of the language. Good programming practice. I would definitely read the HOPL material at some stage to gain an insight. C++ FAQs. Addison Wesley. Essentially just your time and effort getting hold of and printing them. I find this very useful. Obviously C++. Best coverage of the STL that I have seen! If you are going to get involved seriously in C++ programming then I would get a copy of this book too. email: ian. History. 25 to 30 uk pounds.

4.5 and Microsoft 1. map.x and 2. list. deque. I recommend getting hold of the documentation on the standard template library. I have this material up on the King's web server.x.x. Windows 98 and NT4 – Microsoft C++ Release 5.x and Windows 3.chivers@kcl.uk .Sun's compiler Variety of pcs running DOS 6. bitset. stack. These include:– DEC VAX running VMS – DEC's compiler DEC Alpha running VMS – DEC's compiler SUN UltraSparc running Solaris – g++ SUN UltraSparc running Solaris .1 © Ian D Chivers email: ian.x – Borland 4. Some of the examples in these notes will not compile/run with some of the above compilers.ac. I have used a variety of compilers during the development of the notes and examples. queue.Chapter 1 Overview 16 the standard template library:– containers: vector. various betas of 6 and the final release of 6. Variety of pcs running Windows 95. Contents of the standard The following provides a brief coverage of the C++ standard:– 1 General 2 Lexical conventions 3 Basic Concepts 4 Standard Conversions 5 Expressions 6 Statements 7 Declarations 8 Declarators 9 Classes 10 Derived Classes 11 Member Access Control 12 Special Member Functions 13 Overloading 14 Templates 15 Exception Handling 16 Preprocessing directives 17 Library Introduction 18 Language Support Library 19 Diagnostics Library 20 General Utilities Library 21 Strings Library 22 Localisation Library 23 Containers Library 1.

and there is no charge. If you have access to a postscript printer and are going to be working with C++ seriously then I'd think about printing the standard. If you want to look at it online then I'd recommend the Adobe Acrobat portable document format (pdf). Whilst you should learn and use the new style it is inevitable that you will have to become familiar with both styles in the short term. These examples are out of date as they are now supported within the language. Firstly because you will have to work with code and examples written in the old style.ac. e. secondly because you will have to use libraries written and compiled in the old style.g. Acrobat readers are available at a number of sites. The course material and examples have been developed with the following guidelines:– to look at a set of commonly occurring problems that need to be solved in most programming languages. Many texts will provide examples based on strings and complex arithmetic. The url is given in the C++ pages.uk © Ian D Chivers .17 Overview Chapter 1 24 Iterators Library 25 Algorithms Library 26 Numerics Library 27 I/O Library A Grammar Summary B Implementation Quantities C Compatibility D Compatibility Features The site at Warwick has several versions of the standard available.6 Coda Be prepared to devote some time to learning C++. thirdly all compilers don't fully support the standard! 1. 1. It is also installed in all of the Public Access Workstation Rooms (PAWS). data types expression syntax control structuring array handling file i/o to look at the object oriented features of C++ to look at the features in the language that support generic programming templates the functionality offered by the standard template library email: ian. The document can be searched using the Acrobat reader. You need to know what is in the language.5 Old and New You will find both old C style and new standard C++ styles examples throughout the notes. they couldn't possibly. I'd look at the chapters on the various libraries.chivers@kcl. Most of the texts in print do not address all aspects of the standard. You can't gain an understanding of 50 years of program language development and a complex language like C++ without some effort on your part.

I teach on several C++ courses and I need to be able to determine which course you are on. 1. 2-3 years. and its support for generic programming through the template facility. Start Netscape and locate the course material on the college web server.kcl. It is important for you to read the notes between the timetabled sessions and also try completing the examples and problems set. Be patient. To develop further you have to get hold of one of the additional books and extend your knowledge beyond the information provided in these notes.chivers@kcl. i. 1. Once you have an account log into the system. 2. Details of how to do this are given in a separate hand-out. Create a file using whichever editor you wish to use. My email address is given in the footer at the bottom of the page. © Ian D Chivers email: ian. competent C++ programmer. Mail me with a short message to let me know how far you have got. Modifying existing programs is a good place to start. 3. Please include details of the course you are attending in the subject heading to enable me to file the replies. We will also be developing computer based learning material as an adjunct to the formal course.ac. its support for object oriented programming. Practice is essential. the functionality provided by the standard template library. I'll be putting all sources on the web server. 5.uk. access to class library guru. practicals and course notes.e. etc. textedit is probably the easiest. Most of the central systems are named after trees. Do you have a user number and password for gum? If not please visit Computer Reception.8 Problems 1. Rome wasn't built in a day. and you can often cannibalise the examples to solve some of the problems that you have. The main system we will be using is the central college unix system – gum. Please try this support material out. Think about how you learn French. 3-6 months writing programs – basic grounding in C++. 4.Chapter 1 Overview 18 Some of the major strengths of C++ lie in the latter areas.ac. It will help reinforce what is covered in the lectures. no access to C++ class library guru. The consensus seems to be:– 20–30 hour course – basic syntax of C++. Please take the time to reply to our questions. vi is not for the faint hearted.uk . To evaluate the courses and the computer based learning material we need your feedback. German. 2-3 years. getting started.7 Course Details The course is organised as a mixture of lectures and practicals as the most effective way to learn a programming language is by using it.

There is a look at the developments from a historical view point. Babel–17 Aims The primary aim of this chapter is to look at some of the languages used in the sciences. Delany. a comparison of their features and a look at future developments. .' Samuel R.2 Introduction to Programming Languages and Object Oriented Programming 'We have to go to another language in order to think clearly about the problem.

in the late 50's. of the background of programming languages and their development.2 Pascal. The language quickly established itself as the language of first choice for numeric programming. It is essential that you develop an understanding of why there are so many programming languages and their strengths and weaknesses. If the only tool you have is a hammer then everything seems to be seen as a nail. This is the date of the first standard.uk . from the viewpoint of languages of use in scientific problem solving. Extended Pascal 1991? Very successful attempt at a teaching language. ANSI & BSI 1982. as the introductory programming language. No one language is suitable for solving all the problems that you will come across. 1966 The original was designed by a team lead by Backus at IBM. 1975.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 20 2 An Introduction to Programming Languages and Object Oriented Programming The intention of this chapter is to examine.chivers@kcl. The following summarises the survey done by Dick Reid taken from a number of editions:– Language 20th 18th 15th 13th Pascal C++ Ada C Scheme Modula Java Modula-2 Fortran SML Turing Miranda Smalltalk Eiffel Oberon ISETL ML Modula-3 ObjPascal Ada95 Haskel Beta Oberon-2 Orwell Prolog © Ian D Chivers 140 101 82 58 50 32 15 14 9 8 4 4 4 3 3 2 2 2 2 2 2 1 1 1 1 144 100 82 56 49 32 15 9 7 4 4 4 3 3 2 2 2 2 1 1 1 1 1 151 87 74 51 51 32 15 9 6 5 4 4 3 2 2 2 2 2 1 1 1 1 1 157 34 73 39 50 35 13 8 6 6 3 1 3 2 2 1 2 1 1 1 1 1 email: ian. ISO 1983. It is therefore quite old.1 Fortran 66. 2. 2. You need to chose the right tool for the job. Note that it precedes both C and Fortran 77. Think about diy around the home.ac. Pascal still is the most widely taught programming language in computer science departments. See the bibliography for a broader coverage.

Simula is a product of the 1960's. It was originally written for a PDP 11 under UNIX.uk/kis/support/cc/fortran/dickreid20. 2. Standard 1989. at:– http://www. ISO 8652: 1987 Attempt to produce a powerful and expressive language by the American Department of Defence. 2. Only 5% or so ended up being written in assembler. New editions come out about every six months. Numeric work in Modula 2 isn't very attractive.kcl. bcpl. Explicit type casts are required in mathematical expressions. The proposed standard alleviates some of the problems in this area. Standard 1996? Wirth's next language after Algol W and Pascal. Introduced modules (hence the name). 1986. b family of languages and these are typeless languages. Standard November 1997 Attempt by Stroustrup to produce an object oriented version of C. small tools. Still largely Fortran 66. from a slow start.txt which is a sorted list by language. It is based on the cpl. 2. is over 15 years old and still leaks memory. There are little or no facilities in the language for the construction of larger code suites. 1978 Modest attempt to update the language. He doesn't keep past editions. See also Ada 95 later. First draft report was 1980.21 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 Simula 1 1 1 1 Blue 1 The first edition was May 1990. email: ian. He had been exposed to Simula early on and realised the benefits of a language like that. C was developed by Kernighan and Ritchie at Bell Labs. 1982. which includes the institutions. Very many good features. Bell Labs was the research laboratory of the Bell Telephone company in the US.kcl.3 Fortran 77. The X library is written in C.6 Ada.uk/kis/support/cc/fortran/sdickreid20. Added BLOCK IF. 2.ac. Given the knowledge of the time a very conservative update to the language. Rivals Ada without much of the complexity of Ada for real time applications. Let down by the delay in getting standardised. Given the very large defence spending budget. I've put up the complete survey. The first version of Simula was available in 1967.txt What is interesting is the following:– http://www. Gaining ground.ac.7 C++. It was designed as a systems implementation language and was used to rewrite some 95% of the UNIX operating system. had the idea of separate definition and implementation.5 Modula 2. even a 1% gain from the adoption of a better programming language will be repaid.uk © Ian D Chivers . K&R 1978. Look at the features of some of the other languages covered here and the dates to see what is meant by this statement. Attempt to produce a professional programmers Pascal.4 C. Given the date of the publication of K&R there was the opportunity to have tidied the language up somewhat.ac. Where is your institution? 2. The UNIX tools are written in C and are a very good example of what C is best at: the construction of sharp. got rid of some of the idiosyncratic syntactic sugar of Pascal. better array subscripting and corresponding do looping. Object oriented programming is not new! Simula was widely used for discrete event simulation.chivers@kcl.

Meyer is a very keen exponent of the benefits of object oriented programming. Numerics © Ian D Chivers email: ian. Extension of access types. Meyer's book on object oriented software construction is an extremely good introduction to OO programming.chivers@kcl. He highlights some of the weaknesses of C++. and Wirth having to take over the operating system course at ETH. 2. These are:– Annex C. Oberon replaced Modula 2 in 1989 for teaching purposes at ETH. Oberon 2 tidied up a bit. IBM RS6000 and MS/DOS by 1991. early 1990's. There are several so called Specialised Needs Annexes. Major changes from the 1987 standard are in the areas of:– Support for 8 and 16 bit character sets. 2. He provides both academic and commercial courses on C++ and Eiffel. Real-Time Systems Annex E. Partly driven by the visit of Wirth and Gutnecht to Xerox PARC. 1988 Date is the publication of Object Oriented Software Construction. Oberon is the largest moon. He clearly highlights some of the major pitfalls.11 Ada. library units.uk . Richard Wiener. DEC. It is a research vehicle for Wirth and the CS department at ETH in Zurich. Another extremely worthwhile acquisition is Software Development Using Eiffel: There Can Be Life Other Than C++.8 Oberon 2. I hope to be able to make available an Eiffel compiler for the alpha in the near future. 2. Efficient data oriented synchronisation. Eiffel is an attempt to produce an industrial strength OOP language.ac. SUN. Modern language. First operational system by the late 1980s. Some of the problems here may be remedied in the near future with the progress being made on the standardisation front. Very clean and simple OOP language. Distributed Systems Annex F. Late 1980's. ISO 8652: 1995 Latest standard.9 Fortran 90. 1991.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 22 2. Oberon was simpler than Modula 2. Meyer. Information Systems Annex G. Object oriented programming with run-time polymorphism. The language of first choice for people involved in numeric programming. Modern object oriented language. Name arises from the Voyager probe taking pictures of Uranus. Ported to a Apple MAC. Prentice Hall. Free versions available from the ftp server at ETH. Let down badly by continual development and lack of a standard. Good information hiding and powerful mathematical capability. If you are going to attempt a reasonable size application in C++ using OO techniques then you should read this book. interfacing to other languages. Limited OO capability. Systems Programming Annex D.10 Eiffel.

unlike portability at the source code level – which is what we expect with most conventional languages. Whilst it has its origins in C++ it has dispensed with most of the dangerous features. Sun over the next few years ended up developing Oak for a variety of projects. It has built in garbage collection – no dispose! It has no pointers – everything is passed by reference! It is multithreaded. email: ian. which makes it a delight for many applications. Development environments are becoming widely available to aid in this task.13 Visual Basic This language is a development by Microsoft to enable visual user interfaces to be programmed easily.g. 2. Oak was the outcome of Gosling's frustration. This is portability at the object code level. It has a extensive windows toolkit. At round about the same time James Gosling (mister emacs) was starting to get frustrated with the implementation of an SGML editor in C++.x. It has subject to continual development and offers one of the easiest ways of developing a windows style program for a pc running Windows 3. 95. It wasn't until Sun developed their own web browser. Everything is a class. e. 98 and NT. It achieves much of what Visual Basic offers but within the framework of a far more powerful language. The emphasis is on highlighting the strengths and weaknesses of languages used mainly in the scientific area.uk © Ian D Chivers . Further compounded by the different virtual machines available. It is OO throughout.23 An Introduction to Programming Languages and Object Oriented Programming Annex H.chivers@kcl.12 Java Bill Joy (of Sun fame) had by the late 1980's decided that C++ was too complicated and that an object oriented environment based upon C++ would be of use. Hotjava that Java as a language hit the streets. Safety and Security Chapter 2 2. Java is a relatively simple object oriented language. may be achieved using a different mechanism not supported ? unable to verify adequately at the time of writing In all cases please see the more detailed coverage that follows. 2.ac. the so called AWT that was in the original release of the language and Swing that came in later. And as the saying goes the rest is history. It is interpreted and the intermediate byte code will run on any machine that has a Java virtual machine for it. Finally it is fun! Major drawback is the rapid development of the language and the large number of different versions. The following symbols are used:– Y supported y supported with qualification.14 Language Comparison The following page has a simple language feature comparison.

Y Y Y Y Y ? variables Inheritance .Y ? ? Tasking Exception ... 2 – Replaced by references © Ian D Chivers ? S Y Y Y programming email: ian.Y Y binding Operator .chivers@kcl.. 1 – Against the spirit of object oriented programming.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming Simple Program Language Feature Comparison Fortran 66 77 90 Pascal Modula 2 Oberon 2 P M2 O2 75 82 82 96? Y Y Y Y Y ? Y Y Y Y Y C C++ Ada Java 24 Year Feature Independent compilation Separate compilation Concrete data types Abstract data types Dynamic arrays Modules See below Numeric Polymorphism See below General Polymorphism Pointers 66 78 91 C 78 89 Y Y Y - C++ 86 97 Y Y Y Y Y y y 87 95 199? Y Y Y Y Y Y Y Y Y Y Y Y Y y y Y Y Y Y y y Y 1 Y Y y - - - Y Y Y ? Y Y Y Y Y Y Y Y Y Y ? S Y Y Y Y Y 2 Procedure .? ? Y ? Handling These are some of the major features that we need to look at when comparing languages and looking at the development of programming languages.uk ...ac..Y Y Y overloading Threads .S M single/mult Dynamic .

K and R. Ken Thompson. Mossenbeck. Major development and first operational compiler 1970. 2.15.15. Pascal: Preliminary version 1968. Independent Compilation The ability to break a problem down into parts and work on one part at a time. Major step forward in the construction of more complex programs. Technical report March 1980.g. mix integers and reals (both of one or more underlying representations) without casting beemail: ian. The C Programming Language.15 Language Features It is illuminating to look at the languages from the viewpoint of their features and functionality. The Oberon System. A major step forward. User has to know about the implementation however. 2nd edition. 2. Standard 1987. Forcheck is useful for Fortran 66 and 77 programmers.chivers@kcl. N.. Java: Exact date not well defined. 2. 1989 ANSI C Standard. Ada: 1980 original definition. Software Practice and Experience. No checking between compilation units. Modula: Defined experimentally 1975. Lint helps out with C.3 Abstract Data Types The twin concept of data types and procedures that manipulated the data. User Manual and Report 1975. C++: C with classes. 1970. 1979-1983 From C with Classes to C++. The Programming Language Oberon 2.uk © Ian D Chivers .15. 1982-1985 Release 2. e. Object Oriented Programming in Oberon 2. User Guide and Programmer's Manual. 1986 Stroustrup.5 2.6 Numeric and General Polymorphism Numeric Polymorphism In the simplest case the ability to have so called mixed mode arithmetic expressions. First distributed compiler March 1981. 1991.1 Separate Compilation As above with checking across compilation units. Hopefully the standardisation effort will make life easier! 2. 1st edition.15. 1991. The C++ Programming Language. Mossenbeck and Wirth. Reisser . Oberon 2: 1988. Hiding the internals from the calling routine.0: 1985-1988 Stroustrup.4 Dynamic arrays Arrays that are allocated dynamically at run time. The C++ Programming Language.15.ac. Standard 1997. 1978. C: 1969. 1991. B. 2. Wirth.15. First implementation of Modula 2 1979. Latest standard is 1995. M Richards: BCPL A Tool for Compiler Writing and Systems Programming. Programming in Modula 2 1982. The Programming Language Oberon. 1993. 1973 publication of first revised report. Lilith research project 1977.2 Concrete Data Types The ability for the user to define data types that mapped directly onto their problem. 2.25 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 Dates Fortran: The dates are the dates of the standards.

Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 26 tween one type and another. Allows the user to extend an existing type without having to know what is going on.g. This is a powerful program decomposition tool.15. It is assumed that you know what you are doing. Multi-dimensional structures are easily programmed using pointers. trees. 2. Given that C++ has 47 operators it poses problems of readability and comprehensibility with most other areas.15. e. At the next level the ability to call in built functions with numeric data of one or more types. 2. The major problem is that the user is provided with very little help if they are programmed incorrectly. oct-trees etc.11 Dynamic Binding The second of the two major features of OO programming. They normally have a well controlled mechanism for making visible what the external. © Ian D Chivers email: ian. Very useful to people with numeric problems. 2.ac. In Java all objects are accessed via an object reference.7 Pointers and References Pointers in a programming language extend the range of problems that can be solved considerably. The restrictions that C++ has in this area will be looked at later. The explicit type casting required in some languages means that they are not widely used for numeric programming. equipment interfacing. quad-trees.uk .8 Procedure Variables An elegant way of extending the expressive power of a language. linked lists. calling routine needs to have access to.15. embedded systems and parallel programming. Languages that support OOP have to offer the last kind of polymorphism. Classes and packages are two terms also used. When you see an object variable in a Java program you actually see a reference to an object.15.9 2. and so does the exact functionality that these different languages support. Modules The primary purpose of modules is to provide the ability to group related functions and procedures.10 Inheritance The first of the two major step towards OO programming. 2. Finally the ability to create one's own functions that accept numeric data of a variety of numeric types.15. Provided in a limited sense via procedure variables in older languages.chivers@kcl. 2. This has been in Fortran from a very early stage.15.13 Threads/Multitasking Multitasking and/or threads are needed in a programming language when solving problems in the areas of real-time systems. Terminology varies with programming languages. General Polymorphism OO programming languages have to offer this functionality. queues. 2. Quite old.12 Operator Overloading Syntactic sugar in many ways and over valued.15. We will look into the concept of references in much greater detail throughout the course.

Class Extensible abstract data type Object Instance of a class Message Procedure call. 2.16. It has had a great effect on program language design and most languages now support a minimal set of control structures. This is essential reading.3 Information Hiding – Modules A major step forward in the development of programming languages.chivers@kcl. 2.4 2. parallel programming and robust systems. embedded systems.16.16 Some Important Milestones in Program Language Development We look here at some of the major steps forward in the way we approach problem solving using programming languages. verifiability.15.17 Terminology of Object Oriented Programming The following provides a link between conventional programming language terminology and that used in object oriented programming.16.27 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 2. dynamically bound Method Procedure of a class. The ideas are very well covered in the Dahl. Two languages that offer support in this area are based on Fortran 90 and C++. Structured Programming Structured programming in its narrowest sense concerns itself with the development of programs using a small but sufficient set of statements and in particular control statements.16. Hoare text. modifiability and maintenance of programs.ac. email: ian. 2. See Mossenbeck for a good treatment of this. 2. Concrete vs Abstract Data Types With a concrete data structure you have to know how the data structure is organised explicitly. Essential reading.14 Exception Handling Exception handling is needed in a programming language when solving problems in the areas of real-time systems. With abstract data types the internals are hidden from you and all you see are a set of procedures that provide the functionality you want. The paper by Parnas addresses the idea of information hiding and the module concept is one that a number of languages now offer to help in this area.1 Stepwise Refinement The original ideas are very well expressed a a paper by Wirth entitled Program Development by Stepwise Refinement. comprehensibility.2 Data Structuring.uk © Ian D Chivers . We'll come back to the whole area of object oriented programming after a coverage of the basics of C++. A brief coverage is given below. Dijkstra. Often people adopted the following methodologies without having features in a programming language that actually supported them.18 Parallel Developments With the increasing availability of computers with multiple processors at ever decreasing costs the importance of languages that support parallel computation increases. 2. published in 1971. equipment interfacing. In a broader sense it subsumes other objectives including simplicity. 2.

. data abstraction and information hiding. We need to look at the way our appreciation of how to use programming languages developed and what we needed from them as the problems we tackled became more complex. From its very beginning HPFF included most vendors delivering parallel machines. Dijkstra's concept of structured programming. OOP.uk . Wirth's stepwise refinement and Parnas's information hiding all contribute to a software development milieu that promised to become increasingly systematic and scientific. If the problems you have don't warrant it you may never need to devote the time and effort to gain complete mastery of a powerful and complex language like C++. To quote Friedman:– Object oriented programming makes good on the promise of structured programming.2 2. to a great extent. . fulfils that promise. The major thing we need to consider is how to extend the functionality of an existing program. including massively parallel SIMD and MIMD systems and vector processors. a number of government laboratories and many university research groups. Fortran 2000. November 1994 The High Performance Fortran Forum (HPFF) was founded as a coalition of industrial and academic groups working to suggest a set of standard extensions to Fortran to provide the necessary information.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 28 Parallel Fortran – Fortran 95. 2. MPI. It takes the concepts of data abstraction. © Ian D Chivers email: ian.18.19 Object Oriented Programming Object oriented programming is characterised by two main concepts:– inheritance. Instead of passing data to procedures the user asks objects to perform operations on themselves.18. Its intent was to develop extensions to Fortran that provide support for high performance programming on a wide variety of machines. A complex problem is viewed as a network of objects that communicate with each other. dynamic binding. version 1.1.chivers@kcl.1 Parallel C++ Similar developments are in the pipeline for C++. SMP and MPI are two other developments in this area. A number of suppliers now provide HPF Fortran extensions and these are generally based on Fortran 90. rather than Fortran 77. data program and control. and information hiding and refines them in a cohesive world view. Public input was encouraged to the greatest possible extent. Fortran 95 and 2000 offer support for parallelisation. HPF To quote from the HPF Language Specification. It implements in a very practical way the principles of program decomposition. To make sense of the benefits of OOP we need to have a good understanding of the strengths and weaknesses of the traditional programming paradigm. It ties together and provides a framework for abstraction and structure at all levels. The benefits of OOP come with programming in the large. OOP picks up where structured programming methodology leaves off. 2.ac. modular decomposition. SMP. data objects are active entities..

You are unlikely to be out of work if you get to be a good C++ programmer. 2..1 Smalltalk – 1978 The text I recommend is Smalltalk 80. Myhrhaug and Nygaard. notable graphics programming.. It is of course also used in a wide range of other application domains.20.C++ is a general purpose programming language. 2. It is enormously popular.20. but am unsure as to what platform it might be available on. In their words .. 2.uk © Ian D Chivers ... the ultimate goal was to create a system for personal workstations that was not only powerful and convenient for practical use but also describable and explicable in a convincing way. Wirth has spent a number of periods at Xerox Parc and that is reflected in Oberon 2.5 email: ian.20. Algol 60 based.20. This was what the language was used for whilst I worked at Imperial College before I came to King's in 1986. Dahl. Regarded as a pure OO system by most people with everything an object. Stroustrup got many of his ideas from Simula.. Goldberg and Robson. and there are a very large number of jobs advertised for people with C++ skills. 2. its core application domain is systems programming in the broadest sense. Ideas are drawn from Simula and the vision of Alan Kay. We take windowing systems for granted these days on many of the systems we work with from the pc with Windows.20 Object Oriented Languages The ideas are not new. Steve Jobs was heavily influenced by and the Apple Macintosh owes a big debt to the Xerox Parc people.4 Oberon 2 The language has its origins in a visit that Gutnecht and Wirth made to Xerox PARC in 1985. I'm informed that the Channel Tunnel software uses Eiffel! I am looking at getting hold of an Eiffel compiler at this time. The text is a relatively easy read. As is has its origins in Ada is is also a language that offers far greater support for error protection and safe code. They are the first people to use the concept of a class.3 Eiffel Object Oriented Software Construction is dated 1988. C++ supports inheritance through class derivation. I'd recommend it if you are involved in discrete event simulation.chivers@kcl. The latter chapters look at Eiffel in some depth.. As stated earlier the first four chapters address OOP. Simula – 1967 The seminal text on OOP is Simula BEGIN.2 C++ In Stroustrup's words .29 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 2. Birtwistle. They worked at the Xerox Palo Alto Research Centre (Xerox Parc) Learning Research Group. They had originally decided to use Modula 2 but made the decision to strip out some of the 2. Dynamic binding is provided by virtual class functions. They decided to design and implement a new operating system. The Language and its Implementation. Achieves much of the power and expressiveness of C++ without the complexity..20.ac. The book is very well written if a little dated today. to Unix workstations with their X windows interfaces and of course the first to bring them to the mass market – the Apple Mac.

This is well written. If you want a job in the defence industries. Sun. effort and money.ac. is a good introductory text and combined with OOP in Oberon 2. support for texts and fonts. diskette. and comprises a kernel a dynamic loader and garbage collector a file system drivers for disk. Versions for other platforms are available. It is unusual in that it is the product of one company. Ada 95 Whilst I do not have access yet to an Ada 95 compiler from what I've read it looks a very good language. Well worth a look at. printer and a bit mapped display. or see yourself working with real time embedded systems then this is certainly a language to consider looking at.. asynchronous and synchronous communication. There is a lot of documentation that comes with the system and this can be printed. Ada 95 is the first language that has been standardised with OOP in mind. The outcome was Oberon. a text editor. I'd recommend 8Mb of memory and an 80486 with 1024*756 display. Barnes. The object code size of the outer core of the Oberon system is 200K. If your are familiar with Pascal or Modula 2 then I'd recommend Oberon very highly to see what OOP has to offer. local network services. It is hoped that it will pass out of Sun's hands in the near future into the mainstream of language standardisation. I've tried at home on a 20 MHz 80386 with 5 Mb of memory – a bit slow. IBM have taken it on board in a big way and so have Microsoft. a window subsystem. 2. and there is also a look at the changes from the original version to 95 available on the web. The language was defined in 1986. the Oberon compiler.7 © Ian D Chivers email: ian. Reiser and Wirth.20. A text I'd recommend is Programming in Ada 95. They both realise the potential earning capacity of Java and the internet. Due to long file names and multithreading requirements needs operating systems like Windows 95 and above. The standard is available from a number of ftp servers.chivers@kcl. rather than the subject to formal language standardisation like the majority of the other languages covered in this chapter. Programming in Oberon..Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 30 features of that language and add a very small number of features.20. 2. Educational versions of the system are available from the ETH ftp server. Very low cost in time.uk . The system integrates very well with both Windows on the PC and Apple macs.6 Java Java is a recent OO language. Mossenbeck. Freely available if you have internet access. you have sufficient information to get started.

2 email: ian. data abstraction – objects should be described as implementations of abstract data types.chivers@kcl. multiple and repeated inheritance – it should be possible to declare a class as heir to more than one class and more than once to the same class. From what I've seen of the draft standards it will be a powerful and expressive language. These are given below:– 2. and every high level module is a type.ac. inheritance – a class may be defined as an extension of restriction of another.uk © Ian D Chivers . I don't have completely up to date information on what is likely to be in the Modula 2 standard at this time.31 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 2.21.1 object based modular structure – systems are modularised on the basis of the data structures. The work of Meyer and Rumbaugh et al are both well regarded. Standard versions of the language look like being quite expensive and it is unlikely that we would be able to make available a compiler on any platform given the proposed cuts in expenditure by the various government funding bodies. The two that follow fit into this category. without programmer intervention. 2.1 Modula 2 The original language was a major advance over Pascal.22 The OO Approach We will look at two approaches here. If you have a background in the relational database area then 2.22. You may disagree with one or more of the above and some of the above are capable of arousing very strong views in the programming language world! Essential reading for large scale systems. automatic memory management – unused objects should be deallocated by the underlying language systems. Rumbaugh et al This book concentrates on OO modelling. Meyer's Approach Meyer identifies seven steps that lead towards object oriented solutions.22. classes – every non simple type is a module.21. rather than using a particular programming language for OO programming.2 2. Fortran 90 Through the functionality provided via user defined data types and modules it offers support for object based programming.21 Other Languages There are languages that offer limited support for OOP. and we will cover both briefly. See Dupee's MSc thesis for a good coverage of what Fortran 90 has to offer here. It corrected many of the deficiencies of Pascal in a straightforward way. 2. polymorphism and dynamic binding – program entities should be permitted to refer to objects of more than one class and operations should be permitted to have different realisations in different classes.

22. i.y). Now we could write pixel(point.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 32 much of the coverage should be quite familiar. © Ian D Chivers email: ian. object design: build a design model (based on the analysis model) with implementation details. We are interested in shapes and the concepts of moving and drawing. where one class is a sub-type of another. So we could write point(x.23 Simple Example Consider putting together a graphical drawing system.uk . Now consider the concept of a pixel – a point with the added attribute of colour. e. The above have to be done before any code is written. a has a relationship. It has two attributes. e. the functional model: describes the data value transformations within the system.3 identify the classes. Consider the concept of a point. This book is a must for large scale systems. They identify four stages:– analysis: build a model of the real world situation. When you inherit you gain access to the implementation and all that goes with it. As a client you are protected against future changes in the implementation of a class. Practical Steps The two major practical steps are:– 2. where a class is made up of an object of another class. within this discriminate between:– an is a relationship. database. an x and y position. Inheritance commits you to much more than becoming a client. it will be obvious that you will need to go back and redesign and reimplement base classes in the light of experience. Programming is an iterative process and it is inevitable that you will need to cycle through the design and implementation stages as you write code.chivers@kcl. Thus pixel is-a point. implementation: translate into an implementation using a particular programming language.e. We can do this in a very straightforward way using an OO approach. with cross links.ac. In this case a car has-a engine. system design: make the high level decisions about the overall architecture.colour).g. the dynamic model: describes the aspects of the system that change with time. They present a methodology for object oriented development – the Object Modelling Technique or OMT. or hardware implementation. and the three models are orthogonal. and three kinds of models to describe the system:– the object model: describes the static structure of the objects and their relationships. 2. Consider the concepts of engine and car.g. define the interfaces to the classes.

ac. 2.20).1 edit compile link run debug in a loop.33 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 Firstly we have a base abstract class shape with two associated procedures. We will look into this in greater depth later in the course. We just compile the new move and draw procedures and link them in. The major drawback is learning several ways of doing exactly the same thing as we move from platform to platform and from one language to another.24.100. The method resolution is handled by dynamic binding. move(s) draw(s) move(r) draw(r) return(0) } We can now add another shape. circle..chivers@kcl. one to move and one to draw. This method has the advantage of working on most hardware and software platforms. e. Development Environments The traditional working practice for program development involves the following steps:– 2. square s(50..10.24 Other Developments The chapter rounds off with a look at recent developments that have taken place and that apply to one or more programming languages in some cases.length. and still have things work without recompiling the old code.50. We provide two derived classes with two associated procedures:– square(shape. shape(x. How many editors do you know how to use? email: ian.10). rectangle r(100.side) move(shape s) draw(shape s) rectangle(shape.y) move(shape s) draw(shape s) Secondly we then derive other shapes from them.breadth) move(shape s) draw(shape s) Consider the following pseudo-code segment .uk © Ian D Chivers .g.

One major step forward is in reusable software components.chivers@kcl.24. For some alternatives to using Visual Basic to put a windows based front end to a program have a look at the following url for more details:– http://www.24.2 a toolbox of components that can be dragged and dropped onto a screen a screen or form that the user will see – this comprises the user interface a set of properties for each of the components that can be tailored for your own requirements You typically use the mouse to select the item you want from the toolbox ( menu. Skeleton code is often generated for you which you then tailor to your own specific requirements. Increasingly people want easy to use software that almost by definition has a wndows based interface. regardless of the language in which they were created. Sun and Microsoft both made developemnts in this area and we will look at each in turn. Products like this typically have:– 2.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 34 There have also been developments to provide an integrated environment for program development. © Ian D Chivers email: ian. This can be seen as an extensions to the object oriented approach to programming.uk/kis/support/cc/fortran/language. ActiveX is a set of technologies that enables software components to interact with one another in a networked environment. These environments started out as workbenches providing simple access to the editor. OLE or OLE Automatation makes it possible for one application to manipulate objects implemented in another application or to expose objects so that they can be manipulated. This is gradually becoming a reality. A simple example of this would be embedding a spreadsheet of graph from Excel in a Word document. linker etc through simple key strokes and the mouse.ac. The idea is to buy one of the shelf and slot it straight in to our program.html There will be a course later this academic year that looks at this whole area in more depth. form etc) drag and dop onto the form and then alter the various associated setting using the propertiy entries on the right hand side. They have grown very sophisticated. ActiveX First let us define each of the above in turn:– 2.uk . compiler.3 COM – Component Object Model OLE – Object Linking and Embedding ActiveX – Now called Active Technologies Let is look briefly at each in turn.3. 2.24. OLE. There are some problems with this when working with a document on a number of computer systems with different versions of the applications concerned.1 COM.kcl. ActiveX is build on the Component Object Model. Microsoft Visual Basic provides a good example of this. Double clicking on the spreadsheets drops you into Excel. Consider building an application that required a spelling checker. Software Components As the problems that we attempt to solve become more complex and the interfaces we provide become more sophisticated we need better tools to help with program development. Graphical Development Tools There has also been the development of a visual interface to programming.ac.

25 Coda There is a lot that John Backus has to be proud of. Windows programs offer the possibility of solving this problem. C and C++ have a considerable amount of code written in them. Modula. and these are Icon. COM is the foundation technology for OLE and ActiveX. Modula 2. Whither Visual Basic? VB will survive. Prolog and SQL.ac. Pascal. C++.chivers@kcl. No one language is appropriate for solving every problem. correcting some of the program correctness problems that arise in C from array subscript checking. Fortran 77. there was a lot of effort required in moving production code from older languages to their successors. email: ian. scientific.uk © Ian D Chivers . Learning a variety of languages is a good idea.2 JavaBeans JavaBeans is the Java language software component offering. Knowledge of one of the more recent languages (Modula 2 or Oberon) in this family is a worthwhile investment. distributed. system for creating binary software documents that can interact. Sun and Microsoft and battling this one out and there is little love lost between them. and Prolog is a logic based language.3. How widely used it will become depends obviously on the success of the internet and local intranets. type checking and optimisation problems with pointer aliasing and array handling. Whither Java? Java seems to be a language that will survive. The maintenance problems C poses are considerable. object orientded. and we find both commercial and public domain numeric libraries available for most platforms. Sun also provide mechanisms to migrate ActiveX/OLE/COM to JavaBeans.24. JavaBeans extends the Java language write once run everywhere capability to resuable component development. Oberon 2.35 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 The Component Object Model (COM) is a platform independent. The steep learning curve that C++ has poses problems for successive generations of would be C++ programmers. Many factors come into play in real life. engineering and commercial worlds. Object oriented programming is often done in C++. Look at the Computational Science Education paper for an comparison of C. There is a lot of very well written code in Fortran. I've included references to a couple of other languages that you might like to look at. Wirth has a lot to be proud of too with the Algol family of languages – Algol. He achieved a lot with Fortran. SQL is the database language. 2. C++ represents a very major advance over C. Algol W. Snobol. Graphical based systems are invariably written in C++. This is on the college web server. Learning Fortran 90. Java and Visual Basic provides you with a range of very useful skills for work in the academic. pointer manipulation. Fortran 90 and C++. Watch this space as they say! 2. For many applications they offer quite significant advantages over other languages. Oberon. As we shall see Fortran is still the language of first choice for the majority of numeric based problem solving. The sad thing that is that whilst abandoning the previous language enabled successor languages to be well designed and compact. There is considerable interest in JavaBeans because of the platform neutrality of the developed code. Many people need to be able to develop easy to use programs and systems. Icon and Snobol are very good string processing languages.

. The Programming Language Concurrent Pascal. Gosling J. Comprehensive coverage of Ada 95. and co-routines. Very highly recommended. Addison Wesley.. SIMULA BEGIN.. Very interesting comments. Birtwistle G. Concurrent Pascal. Postscript Language: Program Design. A recent update of his previous Ada book. Written by the people who designed and implemented the language.ac. C++. Details are given later. simulation. Programming in Ada 95. The three books provide a comprehensive coverage of the facilities and capabilities of Postscript. Object Oriented Design with Applications. Smalltalk and Simulation Languages by the people involved in the original design and or implementation. Adobe Systems Incorporated. 2nd Ed. 199-207. Smith. Adobe System Incorporated. Addison Wesley. Chartwell-Bratt Ltd. This is the second in the HOPL series. McGraw Hill. Brainerd. A bit expensive at just under thirty uk pounds.. Nygaard K. One is on order at Dillons. Fortran 90 Handbook: Complete ANSI/ISO Reference.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 36 2. Expensive. Still not available at this time. ACM Press. CLU. Myhrhaug B. Algol 68. I've not been able to get hold of a copy of this yet. Dahl O. The Java Programming Language.. © Ian D Chivers email: ian. Barnes J.. The is coverage of Ada. A number of chapters in the book will be of interest to programmers unfamiliar with some of the ideas involved in a variety of areas including systems and models. Looks at the extensions to Pascal necessary to support concurrent processes. Adams. Icon. and the first was edited by Wexelblat. Also has some sound practical advice on problem solving. Postscript Language: Reference Manual. Pascal. A definitive source on the language. but very thorough. Brinch-Hansen P. 1994. Lisp. Annals of the History of Computing. Special Issue: Fortran's 25 Anniversary. Martin. some anecdotal. Not for the beginner. Addison Wesley.M. Postscript Language: Tutorial and Cookbook. Prolog..uk . as there are bound to be major advances in this edition due to his experience between editions. One of the best sources of information on programming language developments. Booch G. June 1975.26 Bibliography Adobe Systems Incorporated. As with the Metcalf and Reid book some of the authors were on the X3J3 committee. Wagener. ACM SIG PLAN. Arnold K. ACM publication. from an historical perspective.. Benjamin Cummings. A complete coverage of the language. IEEE Transactions on Software Engineering. about the early work on Fortran.chivers@kcl. J. C. History of Programming Languages Conference – HOPL-II. Addison Wesley. Addison Wesley. Don't buy or bother with the first edition. Forth.. Formac.

Hoare C. C++ and Fortran 90 using the following five criteria:– numerical robustness. One of the Nutshell series. ISO 9075:1992(E). Cowell J. Springer Compact introduction to Java. Fortran 77. A. D. Fortran 90 and Computational Science. O'Reilly and Associates. .. One of the best currently available.. An introduction to programming using Fortran 90. Java in a Nutshell... W. 27 no 1. Very thorough coverage of the SQL standard. and Deital P. J. Dijkstra E. Deitel H. R. A Guide to the SQL Standard. W. Otten G. Addison Wesley. Insufficient on its own. Chivers I.. Dupee B. Essential reading if one is involved in programming with one or more of these languages. data abstraction. Geissman L. A very good introductory Java text. Flanagan D. Dahl O.. A Study of Object Oriented Methods using Fortran 90.M. Springer Verlag. Friedman L. Structured Programming. Essential Java: Fast. B.. Java language reference and api quick reference.uk © Ian D Chivers . vol. Prentice Hall. History and Future of Fortran. Appendix F provides a useful SQL bibliography. Dissertation 7286. Separate Compilation in Modula 2 and the structure of the Modula 2 Compiler on the Personal Computer Lilith. Aimed at numeric problem solving. Code Generation and the Lilith Architecture. McGraw Hill.J. A look at OO methods in F90. Highly recommended. and Clark M. Date C. ETH Zurich Fascinating background reading concerning Modula 2 and the Lilith architecture.. Prentice Hall. As with many of Dates works quite easy to read.. Chivers I. SQL – The Standard Handbook.. Short article on an early draft of the standard. programming with the Java api. Academic Press. MSc Thesis. email: ian. I've got this on order.. Date has written extensively on the whole database field. ETH Zurich Jacobi C. A copy is available on the college web server.. and Sleightholme J. data parallelisation..D. Computational Science Education Project. Java – How to Program. W.chivers@kcl. object oriented programming and functional programming. January/February 1985. Dissertation 7195.. Comparative Programming Languages.37 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 Cannan S.. rather than full blown OOP. 1972 The seminal book on structured programming. J.. around version 90. and this book looks at the SQL language itself.ac. Four parts are introduction to Java. Data Processing. Introducing Fortran 90.. This paper is a comparison of C. If you want one book on Java then this is the one I'd recommend.

Griswold R. T.. and Robson D. E. New Jersey. Provides a good introduction (if that is possible with the written word) of the capabilities of Smalltalk. The first sentence of the introduction sums it up beautifully: I would like in this paper to present a philosophy of the design and evaluation of programming languages which I have adopted and developed over a number of years. F..A. Polonsky I.. Yellin F.uk . The original definition of the Pascal language.. The Programming Language Ada . namely that the primary purpose of a programming language is to help the programmer in the practice of his art. Basic Programming. Wiley.chivers@kcl.. Knuth D. and thus essential for serious work with C.. The Java API. The definition of the language with a lot of good examples. with an extensive bibliography. Understandably dated when one looks at more recent expositions on programming in Pascal. Knuth writes with an tremendous enthusiasm and perhaps this is understandable as he did design TeX. The original book on Basic by its designers. Addison Wesley. Hints on Programming Language Design. Griswold M. Ritchie D.. I find the pricing a bit much at just under 40 uk pounds a book. Prentice Hall: Englewood Cliffs. Hoare C. E... M. The Icon Programming Language. Prentice-Hall.. The definition of the language. Also provides some short historical material on the language..Reference Manual. The TeXbook. The Knowledge Engineering Review. Gosling J. Kurtz T. Springer Verlag. P. © Ian D Chivers email: ian.R. The BCS Specialist Group on Expert Systems. W. The C Programming Language. Has to be read from cover to cover for a full understanding of the capability of TeX. E. Kernighan B. Also contains information on how to obtain public domain versions of the language for a variety of machines and operating systems.E. Kemeny J. Goos and Hartmanis (Eds). Springer Verlag.. Pascal: User Manual and Report. Prentice-Hall. The original book on the language... Volumes I and II. Logic Programming in the Fifth Generation. Poage J. Griswold R.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 38 Goldberg A. Smalltalk 80: The language and its implementation. Addison Wesley. SIGACT/SIGPLAN Symposium on Principles of Programming Languages.. Jenson K..G. Addison Wesley. Written by some of the Xerox PARC people who have been involved with the development of Smalltalk.. October 1973. The original work on the C language.. A short paper providing a good background to Prolog and logic programming. The Java Team. Kowalski R.ac. The Snobol4 Programming Language. Volume I looks at the core packages and Volume II looks at the Window Toolkit and Applets. Wirth N.

Still not available at this time. Reiser M. L.. A good introduction to the work of Chomsky. Expert Systems and Natural Language Systems.. Possibly the most comprehensive introduction to the history of program language development – ends unfortunately before the 1980's. Parnas D. Chomsky. Also looks at other languages. rather than the language. Addison Wesley. I'm trying to get hold of the latest version. On the Criteria to be Used in Decomposing Systems into Modules. and Reid J. Includes a CD with the Sun JDK. The Oberon System: User Guide and Programmer's Manual.. Looks at a variety of versions of Prolog. Teach Yourself Java in 21 Days. Prentice Hall. Coverage of the use of Prolog in the above areas. Mossenbeck H. Programming Languages: History and Fundamentals.. Most gentle of the books I've found. Prentice Hall. with the added benefit that Chomsky himself read and commented on it for Lyons. The copy I've got is dated 1988. As with the previous book aimed mainly at programmers. How to use the Oberon system. Wirth N. Perkins. A good introduction to Prolog for people with some programming background. 1982. Sams net. A clear compact coverage of the main features of Fortran 8x. Marcus C. and hence not suitable as an introduction to Prolog as only two chapters are devoted to introducing Prolog. Good bibliography. Prentice-Hall. Harvester Press Very personal vision of the uses of computers by children.. Communications of the ACM. Prolog: A Relational Language and its Applications. Addison Wesley. Fontana/Collins.chivers@kcl.ac.. Highly recommended. Prolog Programming: Applications for Database Systems. Reid was secretary of the X3J3 committee.. Good introduction to Oberon..uk © Ian D Chivers . Oxford Science Publications. One of the best introductions to OOP.. Computers and Powerful Ideas... Meyer B. email: ian. Uses Oberon-2 as the implementation language.. Metcalf M.. Lyons J. Springer–Verlag. 15 (12). Whilst obviously Eiffel based well worth a read. Malpas J. Very readable. Reiser M. Fortran 90 Explained. Papert S. 1972.39 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 Lemay L. One of the earliest papers to look at information hiding. Addison Wesley. It challenges many conventional ideas in this area. Object-Oriented Programming in Oberon-2. Sammett J. Mindstorms . Object Oriented Software Construction. Programming in Oberon – Steps Beyond Pascal and Modula. OUP. Revealing history of the developments behind Oberon.Children.

Wirth N.. Sessions on Fortran. Software Development using Eiffel: There Can Be Life Other than C++.chivers@kcl. Greater clarity than the first edition. Very well written. I'd really recommend getting hold of this book if you are going to seriously program in C++ using oo techniques. 2nd Edition. Wiener R. Examples drawn from the computer graphics area.. Program Development by Stepwise Refinement. JOSS. Algol. The chapter on object oriented analysis and design is highly recommended. June 1975. A readable introduction to Ada. Wexelblat. Having been involved in the relational area for over 10 years the book struck an immediate chord. Very highly recommended. Cobol.... Eddy F. April 1971. He knows his stuff! Winder R.uk . with speakers involved in the original languages.Chapter 2 An Introduction to Programming Languages and Object Oriented Programming 40 Rumbaugh J. Byte. and the case studies include an ecological simulation. Prentice Hall. Communications of the ACM. Springer. IEEE Transactions on Software Engineering. Academic Press. Simula. Snobol and APL. GPSS. Lorenson W. a game of strategies and investments and simulated annealing. Blaha M.. Premerlani W. I like this book a lot. Young S. Basic. 145-152. An Introduction to OOP in C++.... An Assessment of the Programming Language Pascal. Wiley. Developing Java software.ac. August 1984.. Roberts G. J. Ellis Horwood. 192-198. Prentice Hall. Well written.. Software Development Using Eiffel: There Can be Life After C++. Seed G.. HOPL I. History and Goals of Modula 2.Object Oriented Modelling and Design. APT. Clear and simple exposition of the ideas of stepwise refinement. Comprehensive introduction to C++ and OOP. Wiener R. Straight from the horse's mouth! © Ian D Chivers email: ian.. ACM Monograph Series. Wirth N. He teaches both academic and commercial Eiffel and C++ courses. Dated in terms of the recent developments with Ada 95. Wirth N. Lisp. An Introduction to Ada. History of Programming Languages. Very thorough coverage of the development of programming languages up to June 1978. Jovial. Prentice Hall.. PL/I. Waiting to get a copy.

386-393. Acta Informatica 1. Amsterdam. On the Design of Programming Languages. Wirth N. Programming in Modula 2. North Holland.. Software Practice and Experience..27 Problems What programming languages are available on the system you work with? email: ian.. 1977.. Highly recommended for anyone involved in large scale program development. From Modula 2 to Oberon. Springer Verlag. Wirth N. IFIP Congress 74. 2004-214 Wirth N. Fascinating background to the development of Oberon. on Prog. Languages and Systems. 3-35. ACM Trans..uk © Ian D Chivers . 2 (April 1988). The Programming Language Pascal.. Modula: a language for modular multi.ac. Type Extensions. Project Oberon: The Design of an Operating System and Compiler. 18. but more generally. Software – Practice and Experience. 1971. not only in the areas of programming languages and operating systems.7 (July 1988). The original definition of the language. 35-63. Gutknecht J. Proc. Wirth N. 7. Wirth N. Essential reading for anyone considering programming in Modula 2 on a long term basis. Addison Wesley. 10. 661-670 Wirth N.programming. 2.41 An Introduction to Programming Languages and Object Oriented Programming Chapter 2 Wirth N.chivers@kcl.

. Aims The aims of the chapter are:– to look at a simple hello world example. Through the Looking Glass and What Alice Found There. 'plenty of practice. to look at a simple numeric example. 'Plenty of practice' he went on repeating. to look at the C++ keywords. to look at the C++ character set.' The White Knight.3 Introduction to Programming in C++ 'Though this be madness. to look at the C++ memory model. to provide definitions of some technical terms used throughout the rest of the notes. Lewis Carroll. to look at a simple string example using C style arrays of char. yet there is method in't' Shakespeare. to look at a simple string example using C++ style string objects. all the time that Alice was getting him on his feet again. to introduce some of the formal syntactical rules of C++.

endl is predefined in C++ to generate an end of line. If we do not want a function to return a value (Pascal procedure or Fortran subroutine) we use void rather than a data type in conjunction with the function name to indicate this. In the case of the special main function. Finally the program terminates with the return(0) statement. The << symbols are classified in C++ as an operator. All programs are called main in C++. When calling functions one is used to them returning a value. in this case Hello World. The examples throughout the notes exist in two forms:– old c style new c++ style and whilst you should adopt the new C++ style for writing all new programs it is necessary to know about the old style to work with existing programs and libraries. The #include line is an instruction to the compiler to make available to the following program unit what is defined in iostream.h. return(0).uk . The # indicates a preprocessor directive. The next line is the start of the program itself. 3. Functions in C++ either return a value (and in this case we are defining main to return an integer value) or not.h in the complete program.h> int main() { cout << " Hello World " << endl. 3.1 Hello World – Old C style The following is a complete old style C++ program. #include <iostream. is the statement separator in C++. } C++ follows in the footsteps of C where there is the concept of the kernel of the language and an additional set of library routines. It is made available by the inclusion of iostream. The } character signifies the end of the program. I/O is not available in the kernel of the language.Chapter 3 An Introduction to C++ 44 3 An Introduction to C++ In this chapter we will look at some simple program examples.ac. We will also look at some of the syntax of C++ programs.2 Hello World – New standard C++ style The following is the new style.chivers@kcl. in this case iostream. There is the concept of compiler preprocessing in C and C++ programs. The <> characters are used to indicate a standard language header file. This is very useful when the overall problem may call for several programs to work together. The next thing of interest is the { character which indicates the start of the program. the C++ language returns the value 0 to the operating system level. The next statement (pronounced see out) prints some text to the standard out stream or screen.h. Text is delimited in C++ with " marks. . They are used to separate items in the output stream. © Ian D Chivers email: ian. There is also the concept of every program unit being a function.

} Here we explicitly qualify cout and endl to show that they are to be found in the standard namespace.chivers@kcl.45 An Introduction to C++ Chapter 3 #include <iostream> using namespace std. The second thing to note is the additional line:– using namespace std. old style. In this case we are defining name to be a character variable and that it can hold up to 20 characters.uk © Ian D Chivers . cout << name . The C++ standard has introduced the concept of a namespace. A blank is a separator. } The first thing to note in the include line is the lack of the ". cin >> name .h> int main() { char name[20] . called std. return(0). The \n within the double quotes generates a new line.ac. Namespaces provide a way of grouping related items.h" within <> brackets. In this case the text Type in your name will appear on the screen. They are analagous to the functionality provided by modules in other programming languages. This helps functions stand out quite clearly from arrays. so the input terminates with the first blank character the user types. return(0). The next statement cin (pronounced see in) reads the text that the user types in and assigns it to the character array name. C++ program. the C++ email: ian.. 3. The next statement cout (pronounced see out) actually prints some text to the screen. In the case of the special main function. int main() { cout << " Hello World " << endl. The next cout statement echos what the user has typed back to the screen. The above line makes available the standard namespace. cout << " Type in your name \n " . #include <iostream. When calling functions one is used to them returning a value. return(0).3 Simple text i/o using C style arrays of char The following is a complete. Note the use of [] in C++ instead of () in Fortran. Finally the program terminates with the return(0) statement. Without this line the above program would have to be rewritten as:– #include <iostream> int main() { std::cout << " Hello World " << std::endl. } We then have a variable declaration. Statements within the body of the program (or function) are separated by a semicolon .

sum = a + b + c . When running this example try typing in more than 20 characters. This is very useful when the overall problem may call for several programs to work together. and uses the new data type – string.uk . average = sum / n . cin >> s . cout << s << endl. cin >> a >> b >> c . cout << a << " " << b << " " << c << " \n" . and no error has has been reported.chivers@kcl. cout << " Sum is " << sum << " \n" .c. } © Ian D Chivers email: ian.0 . cout << " Average is " << average << "\n" . The } character signifies the end of the program.0. } Note again the omission of the ". return(0). average=0.ac. return(0) .h" within the <> brackets. int main() { float a. int main() { string s.Chapter 3 An Introduction to C++ 46 language returns the value 0 to the operating system level. int n=3 . Note also the lack of an explicit size for the string variable s. cout << " Numbers were " . 3. This is a considerable advantage over the old C style array of char.5 Simple numeric i/o This example reads in three numbers from the user and sums and averages them and then prints out the sum and average. #include <iostream> #include <string> using namespace std. We will look into old and new style strings in greater depth in a later chapter.b. 3. It is quite likely that the program will allow you to type in more than 20 characters and echo them back to you on the screen.4 Simple text i/o using C++ style strings This example uses the new standard conformant style. A string is a fully dynamic data type.sum=0. This is one feature of C that makes it more unreliable than other languages. This means that an area of computer memory has been overwritten by these extra characters. #include <iostream> using namespace std. cout << " Type in three numbers \n" .

cout << " Sum is " << sum << " \n" prints out the sum. The semicolon . cin >> a >> b >> c reads three numbers from the input stream. The = symbol is an assignment operator.6 Some C++ Rules and Terminology Simple programs have the following format:– #include <iostream> using namespace std. b. or float in C++ terminology. int main() { // declarations first int i.ac. return(0) ends the program and returns the value 0 to the operating system level. c. } is the end of the program. not a comma as in other languages. n is of type integer or int in C++ terminology. average and n within the declarations.chivers@kcl. Note the use of multiple >> symbols to break up the input stream.uk © Ian D Chivers .47 An Introduction to C++ Chapter 3 The first line #include <iostream> makes available cin and cout so that we can interact with the program. is the statement separator. Spaces are valid separators. cout << " Numbers were " prints out a text message. /* */ // // // // i f x s declared declared declared declared as as as as integer float an array of char a string executable statements go next email: ian. cout << " Average is " << average << "\n" prints out the average. The next line is the start of the program. not a comma as in other languages. We have the conventional use of + and / in arithmetic expressions. b and c together and assigns the result to sum. char x[10]. average = sum / n calculates the sum divided by n and assigns the result to average. sum = a + b + c adds the values of a. string s. The next two lines declare the variables we will be using within the program and their types. The { indicates the start of the declaration and executable part of the program. The next line makes available the standard namespace. Note that we also provide initial values for sum. 3. Note the use again of \n to provide a newline. Note that we use multiple << symbols to break up the output stream. and thus we have a. cout << " Type in three numbers \n" prompts the user for input. In this example we will be working with numeric data. sum and average to be of real type. cout << a << " " << b << " " << c << " \n" echos the numbers back to the user. float f.

unions and casts. and thus one has to be familiar with the conventional C++ style of writing programs. In English countries it is probably safe to assume the that this character set will be the one available. There is no upper bound on the number of characters allowed in an identifier.1 C++ for C Programmers The following are some of Stroustrup's guidelines for C programmers moving to C++. 3. C++ keywords are given below.7 Good Programming Guidelines Every language has its own style. Figure 2 shows the ASCII character set. © Ian D Chivers email: ian. White space characters include blank. Case is significant in C++.uk .3 3.Chapter 3 return(0). Two or three spaces are normally used to indent sections of C++ code. pointer arithmetic. Use indentation and white space to make a program more understandable. It is inevitable that one will end up working with algorithms and programs already written in C++. In practice given a screen width of 80 characters 20 to 30 is a sensible upper bound. inline to avoid a function call overhead.9 C++ Character Set Section r. templates to specify families of functions and types. They must start with a letter or underscore character.4 Pointers Avoid void*. and also is similar to the notational style used by C++ texts. A new standard is becoming increasingly popular where multiple language support is required. horizontal and vertical tab. An identifier in C++ is a sequence of one or more characters drawn from the letters. namespaces to avoid name clashes. 3.ac. Malloc Use new instead of malloc and vector instead of realloc.8.2 3. Macros Use const and enum to define constants. This is a sixteen bit character set. There is further coverage of this in the chapter on string and character data types.4 of the standard only mentions the ASCII character set. The second uses /* to indicate the start of a comment and */ to indicate the end.2. } An Introduction to C++ 48 Variable declarations are normally grouped together at the beginning of the program. Arrays and C style strings Use the C++ STL string and vector classes. There are two ways of providing comments in a C++ program. form feed and new line and comments. 3. 3. This is called UNICODE. It is advisable to adopt a style that one is comfortable with that draws on ones experience of other languages.8 3.8.8. The first uses the // characters and is restricted to one line. The second form can span several lines. digits and the underscore character (_). C++ offers support in this area via wide characters.8. Case is significant.chivers@kcl.

3.chivers@kcl.2 Data Types The following data types were introduced in this chapter:– int integer.11 Key Concepts The key concepts introduced in this chapter are summarised below.ac. Basic structure of a C++ program #include <iostream. . declaration 2. We will look into the whole area of characters. i. the program ends with the } Indentation Indentation is used to highlight the structure of the program and make it more readable by a human being. character sets and strings in much greater depth in a later chapter. . You wouldn't expect natural languages to have identical syntax and semantics.10 Summary Don't be put off by the syntax of C++. 3. is the statement terminator. 3. the . char character string sequence of characters. no decimal point.11.h> int main() { declaration 1.3 email: ian. . execution statement 2. execution statement 1.49 An Introduction to C++ Chapter 3 EBCDIC is another widely used character set. there will normally be one or more executable statements. 3.1 In English:– there will normally be one or more #include lines.11. return (0).e. predominantly on IBM mainframe systems under non UNIX operating systems. the program will end with a return(0) typically. there will normally be one or more delarations.11. .uk © Ian D Chivers . so why expect it from programming languages. It doesn't take long to get on top of that syntax. } 3. the program is always called main. the body of the program starts after the {. float real or floating point.

ac. An Introduction with Advanced Techniques and Examples.13 Problems 1. Addison Wesley. use integers.12 Bibliography An Introduction to C++ 50 I'd recommend getting hold of one or more sources of algorithms in C++.. This paper compares Fortran 77. all it takes is your time and effort getting hold of them. Look at the paper by the Computational Science Education Project for a more up to date comparison. What happens? © Ian D Chivers email: ian. Data Structures in C++ Using the Standard Template Library. object oriented programming and functional programming. Barton J. The compilers give error messages from their view point. One of the few books currently available that look at how to use the STL. Type in the examples in this chapter. Ladd S. This book is not a direct hack from Pascal or Modula. 2. The C++ home page contains a link to the Addison Wesley home page. C and C++ using five criteria. Budd T. The criteria are numerical robustness. What happens with the examples with characters outside of the ASCII character set? What happens when you type in more than 20 characters? Why do you think that is? Is there a compiler switch to trap errors like this? Does the screen representation of these characters match the printed representation? Why do you think that is? Withe the string example how many characters can you type in? 3. Addison Wesley.e. The comments they make regarding Fortran are a little out of date too. A C++ version of his algorithms. The edition I have dated 1994 is out of date as some of the solutions they have would be done better using the features as defined in the C++ standard. C++ Components and Algorithms: A Comprehensive reference for designing and implementing algorithms in C++.. exponential format. Addison Wesley. Some use the old style C++ syntax.R. Nackman L. data abstraction. Look at the error messages that the compilers give you. There are some that are available on the internet. Sedgewick R. M&T Books.B. i. and carriage returns? 4. Fortran 90.. With the examples what happens to so called white space. Again worth getting hold of to see how best to use C++. Algorithms in C++. Try the old and new style variants. He is very cautious. Make an attempt to understand what this means.uk . Scientific and Engineering C++.. This will provide some information on how standard conformant your compiler(s) is(are). Old C style. reals.e spaces. Take up of Fortran 90 has improved in the five years since the publication of this book. Details are given in previous chapter. Aimed at someone with a Fortran background wanting to learn C++. A number of other sources that you might like to look at are given below. Essential if you are going to be involved in serious C++ programming. Hopefully an updated version will become available that uses vectors and valarrays. i. Old C style used. With the last example experiment with the number format.R.Chapter 3 3.chivers@kcl. tabs. data parallelism. You will invariably make typing mistakes. 3.

chivers@kcl.51 An Introduction to C++ Chapter 3 Modify the program to work with five numbers. Write a program that will read in your name and address and print them out in reverse order. 5.uk © Ian D Chivers . How many lines are there in your name and address? What is the maximum number of characters in the longest line in your name and address? What happens at the first blank character of each input line? Are there any characters that can be used to enclose each line of text and hence not stop at the first blank character? email: ian.ac.

const attribute. to introduce the twin concepts of lvalue and rvalue. Lewis Carroll. . The result we proceed to divide. The Hunting of the Snark Round numbers are always false. By Nine Hundred and Ninety and Two: Then subtract Seventeen. the rules for the evaluation of arithmetic expressions. to introduce the concept of a sequence point. and the answer must be Exactly and perfectly true. as you see. and then multiply out By One Thousand diminished by Eight. and Ten.4 Arithmetic and Expressions in C++ Taking Three as the subject to reason about — A convenient number to state — We add Seven. to introduce briefly all of the 45 operators in C++. Aims The aims of this chapter are to introduce:– the numeric data types available in C++. Samuel Johnson. the rules that apply in type conversion.

There are a bewildering number of operators at first sight. It also supports complex arithmetic through the complex class. a_u = a_u *2. unsigned For each of the three integer types there exists corresponding unsigned types. where n is the number of bits in the implementation. int and long int. char p.Chapter 4 Arithmetic and Expressions in C++ 54 4 Arithmetic and Expressions in C++ This chapter looks at the fundamental numeric data types in C++ and the rules for expression evaluation.e.chivers@kcl.ac. ++i) { a_s = a_s*2. i < 129 . cout << a_s << " " << a << " " << a_l << " " cout << a_s_u << " " << a_u << " " << a_l_u << endl. 4.1 using namespace std.h> contains details of what is available for an implementation.signed. The standard header file <limits. int main() { short int a_s = 1. integer and real.uk . short int. a = a *2. unsigned short int a_s_u = 1. Persevere! 4. cout << a_s << " " << a << " " << a_l << " " cout << a_s_u << " " << a_u << " " << a_l_u << endl. cin >> p . long int a_l = 1. What do you think will happen? Also look at <limits. a_l_u = a_l_u*2. Try running the following program on the system you use. i. The storage requirements are the same as for the corresponding signed type. a_s_u = a_s_u*2. a_l = a_l*2. int a = 1. Variations on a theme . #include <iostream> 4. A thorough understanding of these operators is essential for successful use of C++. The standard does not require that they are in fact different from one another. unsigned long int a_l_u = 1. and unsigned arithmetic does not overflow.2 Integer Numeric Type The standard requires three types of integers. They obey the laws of arithmetic modulo 2n. cout << endl. unsigned int a_u = 1. © Ian D Chivers email: i.1 Basic numeric types C++ supports the two numeric data types we are familiar with from other programming languages. for (int i=0 .h> to see what is defined there.2.

the other shall be converted to double otherwise. Do you get any warning messages when you compile the program? What do you notice about the numbers output when the programs runs? We will look at the latter in more depth in the chapter on io. The standard does not require that they are different from one another. the other shall be converted to long double otherwise.4 Numeric Type Conversion Rules if either operand is of type long double.5) shall be performed on both operands then. Treatment of division by zero and all floating point exceptions vary among machines and is usually adjustable by a library function. if either operand is unsigned.ac. if either operand is long.55 } return(0). if either operand is float. Most existing implementations of C++ ignore integer overflows. the unsigned int shall be converted to a long int. } " << f_l << endl. 4. cout << f << " " << f_d < " return(0). The following program provides an example of the use of each real data type supported in C++. the other shall be converted to long. double f_d = 1.0/9. otherwise both operands shall be converted to unsigned long int. if one operand is a long int and the other unsigned int.uk © Ian D Chivers . the other shall be converted to float otherwise the integral promotions (r4. otherwise.0/9.chivers@kcl. int main() { float f = 1. the other shall be converted to unsigned The following type conversion rules apply in mixed mode expressions:– email: i.3 Real Numeric Type There are three real numeric types. if either operand is unsigned long the other shall be converted to unsigned long. double and long double.0/9. otherwise. The standard states The handling of overflow and divide check in expression evaluation is implementation dependent. #include <iostream> using namespace std.h> contains details of what is available for an implementation. } Arithmetic and Expressions in C++ Chapter 4 4. then if a long int can represent all the values of an unsigned int. otherwise. The standard header file <float. float. long double f_l = 1. if either operand is double.

Things are slightly problematic in this area at this time as not all compilers support the full range of include files from the 1997 standard. if ( i > 60 && c == ' ') { cout << endl. } }. } Notice the for loop. It provides a quick and dirty way of retrieving some of the user's work. i.h> int main() { unsigned char c. extended character sets.uk . 4. i=0.) This is an infinite loop.. The loop will actually terminate when end of file is reached. The second breaks the text into 60 character lines. This can be very useful when working with 8 bit data. satellite image data.ac.eof()) break We will look into this in more depth in the chapter on io.get()..e.chivers@kcl. for (. cout << c. if ( c < 32 || c > 127) c = ' '.g. The standard maths library provided with C++ is of type double throughout. e.6 const An integer constant is of the first type that can represent that type.Chapter 4 4.7 Character Data as a form of Integer Data C++ provides us with character data as a flavour of integer data. if (cin. if (cin. 4. return(0).eof()) break. © Ian D Chivers email: i.5 Complex? Arithmetic and Expressions in C++ 56 This is not provided in the base language.) { c=cin. for(. #include <iostream. The following simple program illustrates the use of this data type to recover all of the printable ASCII characters from a file. A real constant is of type double by default. Characters may be signed or unsigned. ++i. The program was developed in response to users with corrupt word-processing files. unsigned int i=0. It is available through <complex> We will look at this later. The next if test replaces all non ascii characters with blanks.

You should also be aware of the rest.ac. The requirements of this paragraph shall be met for each allowable ordering of the sub-expressions of a full expression: otherwise the behaviour is undefined.1 Care must therefore be taken when writing complex expressions. What this means is that we can reference an object in memory without having a name for it. and before the execution of anything in the function body.8. and the order in which side effects takes place is unspecified. //undefined i=7. The following are sequence points:– 4.i++ //i becomes 9 i=++i+1.e. and we will look at this concept again when we use arrays and look at the way pointers are used with arrays in C++. 4. The following table summarises the rules concerning precedence and associativity. Consider the following:– i=v[i++]. 45 all told.chivers@kcl.8. Between the previous and next sequence point a scalar object shall have its value modified at most once by the evaluation of the expression. the order of evaluation of operands of individual operators and subexpressions. Overloaded operators are never assumed to be associative or commutative.i++. Furthermore. Expression Evaluation The standard states in section r. Except where noted.8.uk © Ian D Chivers . when calling a function after the evaluation of all function arguments. the prior value shall be accessed only to determine the value to be stored. i.8. The term lvalue originally meant something that could appear on the left hand side of an assignment statement. and with all of the variants we have 57! A working knowledge of the more commonly used ones is essential for successful use of C++ in numeric programming. Precedence and Associativity.5 on expressions Operators can be regrouped according to the usual mathematical rules only where the operators really are associative or commutative. These are places in the code where all side effects of previous computations have to be completed.4 Operator Summary email: i.3 Operators.2 after the complete evaluation of each full-expression. If your are unsure about the expression evaluation then break it down into smaller subexpressions. Sequence Points Because of the nature of C++ (and C) it is necessary to look at the concept of a sequence point.57 4. //undefined i=i+1 //value of i is incremented 4. The standard states an object is a region of storage: an lvalue is an expression referring to an object or function. All operators associate left to right except for those in the third and eighteenth position in the precedence hierarchy. 4. Lvalue and Rvalue There is the possibility in C++ to be able to allocate and use variables that don't have names.8 Arithmetic and Expressions in C++ Operators and Expression Evaluation Chapter 4 C++ has a large number of operators. the unary and assignment operators.

chivers@kcl.expr expr << expr expr >> expr expr expr expr expr < expr <= expr > expr >= expr 58 expr == expr expr != expr expr & expr expr ^ expr expr | expr expr && expr expr || expr email: i.* ->* * / % + << >> < <= > >= == != & ^ | && || Arithmetic and Expressions in C++ scope resolution global member selection member selection subscripting function call value construction post increment post decrement size of object size of type pre increment pre decrement complement not unary minus unary plus address of dereference create destroy destroy array cast member selection member selection multiply divide modulo or remainder plus minus shift left shift right less than less than or equal greater than greater than or equal equal not equal bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical inclusive OR class_name :: member :: name object.uk © Ian D Chivers .ac.Chapter 4 :: :: .member pointer -> member pointer [expr] expr (expr_list) type(expr_list) lvalue ++ lvalue — sizeof expr sizeof (type) ++ lvalue — lvalue ~ expr ! expr .expr + expr & expr * expr new type delete pointer delete [] pointer (type) expr object. -> [] () () ++ — sizeof sizeof ++ — ~ ! + & * new delete delete[] () .* pointer_to_member pointer -> * pointer_to_member expr * expr expr / expt expr % expr expr + expr expr .

4.4. 4. 4.4.8. 4.9 — [post decrement] lvalue — Decrement after use.4.5 [] [subscripting] pointer [expr] The normal array subscripting operator.4.4 -> [member selection] pointer -> member As above.4.4.ac. 4.4.4.8. [member selection] object.8.8.59 Arithmetic and Expressions in C++ Chapter 4 ?: = *= /= %= += -= <<= >>= &= |= ^= throw .8.8 ++ [post increment] lvalue ++ Increment after use.8.member This operator allows us to select a member of a class.1 :: [scope resolution] class_name :: member This operator allows us to use a name declared two or more times correctly within a name space. 4. 4. email: i.8.4. 4.11 sizeof [size of type] sizeof (type) Used to determine the memory size of a type.6 () [function call] expr (expr_list) The function call operator.4.4.4.8.8.8.2 :: [global] :: name This operator allows to use what would otherwise be a hidden global name.uk © Ian D Chivers . 4. 4.10 sizeof [size of object] sizeof expr Used to determine the memory size of an object. expr There will be more complete examples of each of the following in later chapters.3 .8. 4.8. 4.12 ++ [pre increment] ++ lvalue Increment before use.chivers@kcl.7 () [value construction] type(expr_list) Value construction mechanism. conditional expression conventional assignment multiply and assign divide and assign modulo and assign add and assign subtract and assign shift left and assign shift right and assign AND and assign inclusive OR and assign exclusive OR and assign throw exception comma expr ? expr : expr lvalue = expr lvalue *= expr lvalue /= expr lvalue %= expr lvalue += expr lvalue -= expr lvalue <<= expr lvalue >>= expr lvalue &= expr lvalue |= expr lvalue ^= expr throw expr expr .

16 . Integral promotions are performed. 4. 4.8. 4. This type must be an object type. Also used to identify a destructor.4.expr As stated.8.8.25 ->* [member selection] pointer -> * pointer_to_member The binary operator ->* binds its second operand.4. 4.13 Arithmetic and Expressions in C++ 60 — [pre decrement] — lvalue Decrement before use.ac.8. 4.* pointer_to_member The binary operator .4. 4.Chapter 4 4.4. 4. which must be of type pointer to member of class T to its first operand. 4. which must be of type pointer to member of T to its first operand. The result is an object or a function of the type specified by the second operand.8.4. 4. The expression points to an array. and functions cannot be allocated in this way. which must be of type pointer to T or pointer to a class of which T is an unambiguous and accessible base class.8. The operand must be of integral type.22 delete[] [destroy array] delete [] pointer This form is used to delete arrays.4.4.8. and the result is an lvalue referring to the object to which the expression points.8. The destructors (if any) for the objects pointed to will be invoked.23 () [cast] (type) expr An explicit type conversion can be expressed using either functional notation or the cast notation.19 * [dereference] * expr The unary * operator means indirection.8. The result is an object or a function of the type specified by the second operand.8.8.20 new [create] new type The new operator attempts to create an object of the type to which it is applied.21 delete [destroy] delete pointer The delete operator destroys an object created by the new operator.15 ! [not] ! expr Logical negation operator.* [member selection] object.chivers@kcl.uk .4.24 .8. which must be of class T or of a class of which T is an unambiguous and accessible base class.4. 4. 4.4.4.26 * [multiply] expr * expr Conventional arithmetic multiplication. © Ian D Chivers email: i.17 + [unary plus] + expr As stated.14 ~ [complement] ~ expr One's complement operator. 4.8.18 & [address of] & expr The result of the unary & operator is a pointer to its operand. and the expression must be a pointer.4. 4. 4.27 / [divide] expr / expt Conventional arithmetic division.8.4.[unary minus] .4.8.4. though pointers to functions can.* binds its second operand.

4. 4.8.8.4.32 >> [shift right] expr >> expr Shift right.[minus] expr .40 ^ [bitwise exclusive OR] expr ^ expr The usual arithmetic conversions are performed: the result is the bitwise exclusive or function of the operands.35 > [greater than] expr > expr Conventional relational operator.expr Conventional arithmetic subtraction.4.34 <= [less than or equal] expr <= expr Conventional relational operator. The operator applies only to integral operands.8.29 email: i.39 & [bitwise AND] expr & expr The usual arithmetic conversions are performed: the result is the bitwise and function of the operands.8. The result is true if both operands are true and false otherwise.4.8.43 || [logical inclusive OR] expr || expr The operands are both converted to type bool. 4. 4. 4.8. The operator applies only to integral operands.8. 4.ac. 4.30 .28 Arithmetic and Expressions in C++ % [modulo or remainder] expr % expr Chapter 4 Remainder.8.8.4.8.8.uk © Ian D Chivers . The operands must be of integral type and integral promotions are performed. Left to right evaluation is guaranteed. 4. 4. 4.4. 4.42 && [logical AND] expr && expr The operands are converted to type bool. The operands must be of integral type and integral promotions are performed.8.8. and the second operand is not evaluated if the first is false. 4.4. + [plus] expr + expr Conventional arithmetic addition. 4.38 != [not equal] expr != expr Conventional relational operator.4.8.37 == [equal] expr == expr Conventional relational operator.4.4. 4. The operator applies only to integral operands.41 | [bitwise inclusive OR] expr | expr The usual arithmetic conversions are performed: the result is the bitwise inclusive or function of the operands.4.4.4.33 < [less than] expr < expr Conventional relational operator.4.4.36 >= [greater than or equal] expr >= expr Conventional relational operator. All side effects of the first expression except for destruction of temporaries happen before the second expression is evaluated.8.31 << [shift left] expr << expr Shift left.61 4.4.4. The result is true if either of its operands is true and false otherwise.8.chivers@kcl. 4.

8.47 /= [divide and assign] lvalue /= expr Divide and assign.g.g. e.8.8.46 *= [multiply and assign] lvalue *= expr Multiply and assign.chivers@kcl.57 .4. a=a+expression 4.4. and the second operand is not evaluated if the first is true.g. 4.uk . We will introduce examples throughout the notes as we progress. a=a*expression 4.9 Expression Examples It is not appropriate here to cover each and everyone of the above in great depth. a=a-expression 4.8.4.4.8.4. a=a%expression 4.4.4. e.53 &= [AND and assign] lvalue &= expr AND and assign 4.51 <<= [shift left and assign] lvalue <<= expr Shift left and assign 4. the result is an lvalue if its right operand is. 4. All side effects of the left expression are performed before the evaluation of the right expression.54 |= [inclusive OR and assign] lvalue |= expr inclusive OR and assign 4. otherwise that of the third. It is evaluated and if it is true the result of the conditional expression is the value of the second expression. expr A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is discarded. All side effects of the first expression except for destruction of temporaries happen before the second or third expression is evaluated.8. © Ian D Chivers email: i.4.ac. e.8.4. 4.8.45 = [conventional assignment] lvalue = expr Conventional assignment. 4. a=a/expression 4.8.Chapter 4 Arithmetic and Expressions in C++ 62 Left to right evaluation is guaranteed.8.8.4.g. All side effects of the first expression except for destruction of temporaries happen before the second expression is evaluated. Note that there is no exponentiation operator.56 throw [throw exception] throw expr throw exception 4.49 += [add and assign] lvalue += expr Add and assign.g. e.8. [comma] expr .52 >>= [shift right and assign] lvalue >>= expr Shift right and assign 4.4.44 ?: [conditional expression] expr ? expr : expr The first expression is converted to bool.4.4.55 ^= [exclusive OR and assign] lvalue ^= expr exclusive OR and assign 4.8. e. The type and value of the result are the type and value of the right operand.48 %= [modulo and assign] lvalue %= expr Modulo and assign.8.50 -= [subtract and assign] lvalue -= expr Subtract and assign.4.

l++. int main() { int i=0. cout << ++i << endl. cout << i/j << endl. Type the above in and run it. and hence by implication this will apply to C++ also. int main() { int i=9. } Type this example in and run it. return(0). int j=0.ac. return(0) } The above example highlights the use of the pre and post increment and decrement operators.uk © Ian D Chivers .63 Arithmetic and Expressions in C++ Chapter 4 The following programs and program extracts cover some of the above. #include <iostream> using namespace std. cout << i%j << endl. #include <iostream> using namespace std. email: i. ++k. i=i+1. cout << i/k << endl. int j=0. int k=0. int k=-2. int main() { int i=0. cout << i%k << endl.chivers@kcl. cout << j++ << endl. j+=1. int l=0. Work is underway with the new C standard to make division consistent with the Fortran 90 standard. Consider the following example:– #include <iostream> using namespace std. int j=2.

return (0). light_minute = light_year / ( 365. The Fortran 90 standard tackles this issue with the concept of an equivalent mathematical expression.second .0 * 60. #include <iostream> using namespace std.25 * 24.distance. } Note the use of const to set up light_year as a constant – parameter in Fortran terminology. its core application domain being systems programming in the broadest sense. cout << " " << second << " seconds \n" . © Ian D Chivers email: i.10 Summary As Stroustrup states C++ is a general purpose programming language. where overflow is not regarded as an error.chivers@kcl. As the standard states this is undefined in many cases.minute ) * 60 .46*10E12 . However there are a number of areas that are different and you need to be careful here.elapse . int main() { float light_minute. elapse = distance / light_minute . return(0) } What do you think will be the output of this program? Do we need four ways of achieving the same thing in a programming language? This example is taken from the Fortran 90 text. Hopefully this will improve with the publication of the standard. It is a direct translation.Chapter 4 Arithmetic and Expressions in C++ 64 cout << i << " " << j << " " << k << " " << l << endl. One problem lies in expression evaluation.0 * 10E6 . cout << " Light takes " << minute << " minutes \n" . Another problem comes with unsigned integer arithmetic. In addition C++ is successfully used in many application areas that are not covered by that label. Note however that program correctness is more important than program efficiency. second = ( elapse . and the calculations can continue. C++ shares much in common with other programming languages used for numeric programming.0 ) . Do you get any warnings when compiling this program? 4. minute = elapse .uk . const float light_year = 9. distance = 150.ac. This means that there is a lot of functionality within the language and mastery of it will take time. Another problem is really a quality of implementation issue with regard to floating point error reporting. int minute. This is to provide the compiler writer with the opportunity to optimise the code.

1. One of the easiest ways to write a program is to modify an existing one.1. Remember that you need to gain familiarity with the C++ rules. Try typing in and running the examples given in this chapter.11.11. dealing with the time taken for light to travel from the sun to the earth could form the basis of several other programs. You need to make mistakes and see what goes wrong. What is the time lag in using such a satellite for a telephone conversation? the moon is about 384. some 35. what implications does this have for control experiments on the moon? what is the time lag? the following table gives the distance in MKm from the sun to the planets in the solar system: mercury 57. 2.9 jupiter 778.2 earth 149.11.11.6 mars 227.1.ac.11.4 4.1.11. many communications satellites follow a geosynchronous orbit.3 4.chivers@kcl.65 4.1 4. The example given earlier.2 4. For all practical purposes email: i.3 saturn 1427.4 4.2 Real float double long double Complex – supported via <complex> Character Data as Numeric Data 8 bit signed-128 to +127 unsigned0 to 255 Constants – use the const attribute Operators – 45 but effectively 57 with variants Expressions – the order of expression evaluation is often undefined 4.11 Key Concepts Arithmetic and Expressions in C++ Chapter 4 Numeric Data Types 4.400 Km from the earth (on average).0 Use this information to find the greatest and least time taken to send a message from the earth to the other planets.870 Km above the earth's surface.11.0 uranus 2869. its good enough for this example).6 neptune 4496.9 venus 108. telephone number and sex. 3.11.12 Problems 1. Assume that all orbits are in the same plane and circular (if it was good enough for copernicus.3 4.uk © Ian D Chivers . Modify the program that read in your name and address to read in and print out your age.6 pluto 5900.1 Integer short int int long int 4.

What is the word size? Experiment with multiplication and division to see what messages you get when numbers become too large (overflow) and too small (underflow). Use the following formula:– t=2*pi*sqrt(length/9. Write a program that tests the size and precision of numbers on the system that you are using. and therefore a good candidate for a const statement.uk . Use it. © Ian D Chivers email: i.81) Calculate the period for at least 5 values of the length. 4.chivers@kcl. Write a program to calculate the period of a pendulum. If you have access to anther compiler and or platform and compiler try the above out on that system. The length is in metres and the time is in seconds.ac. 5.Chapter 4 Arithmetic and Expressions in C++ 66 the speed of light in a vacuum is a constant.

h>. to introduce enumerated data types. .5 Strings and other data types 'Don't Panic' Douglas Adams. to look at a number of other c++ concepts. to look at <string. to introduce reference variables. The Hitch Hiler's Guide to the Galaxy Aims The aims are:– to introduce the string data type. to introduce the boolean data type.

int lsize=sizeof(lowercase)/sizeof(char).h> © Ian D Chivers email: i.1 Note here the use of dec.i++) { ch=lowercase[i].1. } return(0). We will look at examples in both styles. for (int i=1.1. 5.i++) { ch=uppercase[i]. uses an array of characters terminated with a null character.uk .1.ac. char lowercase[]="abcdefghijklmnopqrstuvwxyz". The first.i < usize. C Style strings 5. cout << " upper case array size is " << usize << endl.h> #include <string.chivers@kcl. Note also the last character printed out in the loops.h> int main() { char uppercase[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ". old C style. oct and hex to write out integer values in decimal. octal or hexadecimal format.Chapter 5 Strings and other Data Types 68 5 Strings and other Data Types This chapter looks at the other data types available in C++ and a number of other concepts present in C++.1. int ic. The answer of 27 is not one that most people would expect.2 Example 2 The following is another example of C style string usage. } for (i=1 . cout << ch << " = " << dec << ic << " = 0" << oct << ic << " = 0x" << hex << ic << endl. } 5.1 Example 1 Note the values of the lengths of the two character arrays when this program is compiled and executed. char ch. ic=int(ch).i < lsize. #include <iostream. int usize=sizeof(uppercase)/sizeof(char). The second treats strings as objects.1 Character Data or Strings Sequences of characters or strings can be represented in C++ in two ways. ic=int(ch). cout << ch << " = " << dec << ic << " = 0" << oct << ic << " = 0x" << hex << ic << endl. 5. #include <iostream.1. cout << " lower case array size is " << lsize << endl. We will not look at this way of doing things in more depth until we have covered pointers.

1. Not quite what some people expect! strcat concatenates the second string to the first.s2) Compare strings s1 and s2. Some of the benefits of this data type over C style strings include:– 5. strcat(line. strcpy(line.s2) Join string s2 to string s2. vectors and valarrays.uk © Ian D Chivers . 5.1.1. strcpy.1. and the arguments are the data. 5.1." Chivers"). What we have in the above is a syntax that binds togethor data and an operation.1. subscript checking through the use of at() – the out_of_range exception is thrown. we will look into this in more depth in the chapter on arrays. strlen and strchr are the operations or actions we want carried out.69 Strings and other Data Types Chapter 5 int main() { char line[80].c) Locate character c in string s."Ian"). 5. The following provides a summary of the new class.1 assignment s1=s2 5.6 strlen(s) Return the length of string s.1. string assignment results in copies – this avoids the problems associated with multiple pointer references to one memory location.ac.4 strcat(s1. 5.1." David").1. The following are some of the old C style string functions. C++ Style strings – <string> Access to this data type is provided in the <string> include file. This is a syntax that you should be familiar with from your experience of functions.2 more functionality.1. procedures or subroutines in Fortran.1. return(0). strcmp. taking care of the \0 terminator. strcat(line.2.1. strcat.5 strcmp(s1.3 strcpy(s1.2.7 strchr(s.1. 5.chivers@kcl.2 character access s[i] email: i. } strcpy copies a string from the second argument to the first.s2) Copy string s2 to string s1. comparisons can be done using the conventional relational operators. Pascal etc. 5. cout << line.

length.3 comparison s1==s2 s1!=s2 s1<s2 s1>s2 s1<=s2 s1>=s2 5.Chapter 5 Strings and other Data Types 70 s.ac.remove(start.10 removal s. Notice also the new object oriented syntac for binding togethor data and an action:– © Ian D Chivers email: i.2.position) s.insert(position.find_first_of(string.12 resize s.find(string.1.4 concatenation s1+s2 s+=s1 5.position) s.8 iterators s.2.chivers@kcl.1.13 search s.2.end() 5.substr(position.2.resize(integer.1.1.string) 5.length) 5.7 insertion s.character) 5.length) 5.2.2.resize(integer.1.11 replacement s.find(string) s.1.2.position) We will look at examples of string use through the rest of the course material.2.1.1.6 i/o stream << s stream >> s getline(stream.1.1.9 length s.uk .string.find_first_not_of(string.length() s.2.empty() 5.begin() s.5 constructors string s string s("some text") string s1(s2) 5.replace(start.character) s.1.string) 5.2.2.character) 5.

s+=" Chivers". bool is a unique signed integral type.uk © Ian D Chivers . A bool value may be converted to int by promotion: true converts to 1 and false converts to 0.action() Strings and other Data Types Chapter 5 and contrast this with the other syntax for strings using arrays of char. Note the use of & to denote that the variable is a reference variable. } Note that the string is fully dynamic and grows to the size required. Things will gradually become more familiar as we progress through the material and examples. The relational operators yield bool values. A numeric or pointer value may be implicitly converted to bool. int main() { string s. Guidelines for use It should be obvious that the new C++ style strings offer substantial advantages over the old C style strings.chivers@kcl.ac. 5. This means that two or more variables can refer to the same variable or storage location.71 data. Most of the older texts on C++ will use the old C style strings.1.3 Reference Variables A reference variable provides an alias mechanism within C++. we can use use iterators when we want speed – covered in the chapter on the standard template library.1 of the standard introduces boolean as a genuine data type for the first time into C/C++. we can then catch exceptions – covered in more depth later. return(0).6. email: i. s+=" David". 5. using the new style syntax. and some recommendations about usage include:– 5. The following program illustrates the concept. The & character is called the address of operator in C++.2. We will look at more string examples throughout the notes.2 Boolean or Logical Data Section r. Try running the program and looking at the output. Note also the better syntax for string manipulation using conventional operators. #include <iostream> #include <string> using namespace std.3. cout << s << endl.1.14 Example 3 This is a version of example 2.3 we can pass and return strings by value and let the system manage memory we can use subscripting when we want range checking – covered in the chapter on arrays and vectors. A zero value becomes false and a non-zero value becomes true. We will look into this area in greater depth in the chapter on pointers. s=" Ian". 5.

cout << i << endl.chivers@kcl. cout << ok << endl. } We can also use enumeration types to provide boolean variables if they are not supported in the compiler you use. } © Ian D Chivers email: i. cout << ok << endl. Interestingly this feature has been removed from Oberon. ok=false.Chapter 5 Strings and other Data Types 72 #include <iostream. 5. cout << today << endl. This is a feature of the Pascal. and we will come back to guidelines for the use of reference variables later in the course. sunday}. int &j=i.ac. today=monday. thursday. #include <iostream.4 Enumeration Types The following program illustrates the use of enumerated types in C++. } The three main uses of reference variables are:– as argument types in functions.uk . with overloaded operators. with return values from functions. wednesday. boolean ok=true. but not Fortran. return(0). cout << i << endl.h> int main() { int i=10. Modula2 family of languages. j=20. tuesday. day today. cout << j << endl. cout << j << endl.h> int main() { enum boolean { false.h> int main() { enum day {monday. return(0). They provide a very secure program construct when a data type can map onto a subset of integers. return(0). friday saturday. This is illustrated below. #include <iostream. true }.

#include <iostream.6 Scope With all programming languages there is the concept of the scope of a name. } 5. using a variable within an inner block will hide a variable of the same name within an outer block. The following program illustrates this. } return(0).73 5. cout << a << endl. int i=0. e.h> int main() { float a.uk © Ian D Chivers . a=(float)i. We can complicate things in C++ by declaring variables of the same name within a program.e. } The { and }define the start and end of a blcok. return(0).ac. b=float(i). convert one type to another. cout << i << endl.g. float b. Within the examples so far the scope of a name is restricted to the file that we are compiling. We will look at the concept of scope in much greater depth throughout the notes email: i. cout << i << endl. a=(float)i. int i=0.chivers@kcl. This is done in C++ using the syntax:– (type) expression or type(expression) The following program is a complete example.h> int main() { float a. #include <iostream. cout << b << endl. cout << i << endl. cout << a << endl.5 Type Conversion Strings and other Data Types Chapter 5 In the previous chapter we looked at writing mixed mode arithmetic expressions and covered the type promotions that took place automatically. { int i=99. There is also the need to cast between types. i.

10. There is also a method of creating objects on what is called the free store using the new operator. © Ian D Chivers email: i. and exists until the block that contains it is exited or left. 5. There are no objects of type VOID. tuesday.7 Void Strings and other Data Types 74 The type VOID behaves syntactically like any other fundamental type. A static object is allocated when the program starts executing and exists throughout the lifetime of the program. 5.10 Key Concepts Data Types 5. 5.1 Sequence of characters as an array of char char x[10].10.10.10. 5. friday}.10.5 Enumerated Types enum weekday {monday.9 Summary Any introductory Pascal or Modula 2 text will have a wide range of examples of the use of enumerated types. 5.1. The most common use is as the type of a function that does not return a result. thursday.1.chivers@kcl.10.2 5.10.uk .8 Memory and C++ C++ provides a number of ways of working with memory and it is necessary to look at the choices on offer. int &j=i.1. 5. I suggest getting hold of one to see how versatile this data type can be. An automatic object is allocated each time execution reaches that point in the program.7 Type Conversion (type) expression or type (expression) 5.6 Void void main() 5. Firstly we distinguish between static and automatic. wednesday. There are some restrictions on its use however.3 Memory static – allocated when the program starts. We will look into this whole area in more depth after the coverage of functions.3 Logical or boolean bool check.10.10. 5.1.4 Reference Variable int i.1.Chapter 5 5. 5.ac.1 Scope Range of the validity of the name of a variable. 5.1. We will look at character data in much greater detail later in the course.2 Seqence of characters as a string string s.1.10.

octal and hexadecimal output. Type in the example one and look at the decimal. 3.75 Strings and other Data Types Chapter 5 automatic – allocated and de-allocated each time execution reaches that point in a program. Type in and run the reference variable example.ac.11 Problems 1. covered later. What will be the output? How does this compare with Pascal or Modula 2? email: i. 5. Type in and run the enumeration example.uk © Ian D Chivers . Is this what you would have expected? Is this consistent with the ASCII character set? 2. Use you own name. Type in and run the second example using strings. Can you think of any use of reference variables at the moment? 4.chivers@kcl. free store – allocated and de-allocated use new and dispose.

gravely 'and go on until you come to the end then stop. Aims The aims of this chapter are to:– look at the basic array syntax in C++.' the King said. look forward to the use of some of the additional features of C++ that enable us to make array handling more understandable and reliable. look at array element ordering in C++.6 Arrays. look at the associated control structure. look at the new facilities provided by the vector class. 'Begin at the beginning. . the for loop. Alice's Adventures in Wonderland. look at the new facilities provided by the valarray class.' Lewis Carroll. Vectors and valarrays in C++ 'Where shall I begin your Majesty' he asked.

Lets look now at the for loop in C++.average=0. but don't panic. The second thing of interest is the array indexing. However BASIC is a programming language that offers arrays starting at 0 and 1 as an option in most implementations. The general syntax is for ( inital statement . for (month=0.Chapter 6 Arrays. one per line \n" .1.1 6.month < 12 .1 Old C Style arrays One d example – Monthly Rainfall #include <iostream.chivers@kcl. this is the first element. ++month) cin >> rainfall[month]. expression 1 . expression 2 ) © Ian D Chivers email: i. for (month=0. You should use the new vector and valarray classes in preference to the old C style array. float rainfall[12] This declares the array rainfall to hold 12 elements. int month . 6. for (month=0.h> int main() { float sum=0. you will have to work with code written in the old style. } The first thing of interest is the array declaration. Vectors and Valarrays in C++ In this chapter we will look three different ways of using arrays in C++.ac. including:– not all compilers support vectors and valarrays fully. We are used to arrays starting at 1 – naturally.0 .month < 12 .uk . return(0).0. cout << " Type in the rainfall. A little odd at first. Zero didn't exist in mathematics for quite some time. you will have to work with libraries written in other languages and these will only work with the old C style arrays. However you have to know about the old C style arrays for a variety of reasons. cout << " Average is " << average. the second looks at the facilities provided by the vector class. float rainfall[12] . and the third looks at the facilities provided by the valarray class. you will have to interface to libraries written and compiled using the old C style arrays. average = sum/12. The first is the old C style array mechanism. ++month) cout << month << " " << rainfall[month] << " \n " . Vectors and Valarrays in C++ 78 6 Arrays.++month) sum = sum + rainfall[month].month < 12 . The use of the [] means that arrays stand out quite clearly from function references. This goes from 0 through 11.

79

Arrays, Vectors and Valarrays in C++
statement

Chapter 6

The initial statement normally sets up an initial value for the loop counter. In this case month. Expression 1 is the loop control mechanism. In this case we are interested in stopping once we have processed all 12 months. Expression 2 is normally the loop counter increment mechanism. In this case increment by one. statement is the statement that will be executed whilst expression 1 is true. We will look in more detail at the for statement in a later chapter. One d array – People's Weights #include <iostream.h> int main() { const number_of_people = 10; float sum=0.0,average=0.0; float weights[number_of_people]; int person; cout << " Type in their weights, one per line \n"; for ( person=0 ; person < 10 ; ++person ) { cin >> weights[person]; sum=sum + weights[person]; } average=sum/number_of_people; cout << " sum was " << sum < " \n "; cout << " average was " << average << " \n " ; return(0); }
6.1.2

In this example we use { and } to bracket the statement under the control of the for loop. This enables us to repeatedly execute more than one statement.
6.1.3 Two d Array – latitude and longitude #include <iostream.h> int main() { int latitude,longitude; float height[5][5]; for ( latitude=0 ; latitude < 5 ; ++latitude) for (longitude=0;longitude < 5 ; ++longitude) cin >> height[longitude][latitude]; for (latitude=0;latitude < 5 ; ++latitude ) for (longitude=0;longitude < 5 ; ++longitude ) cout << height[longitude][latitude] << "\n"; return(0); }

Things are now getting a little away from our original real world way of looking at problems. We now have 0–4 everywhere where the real world says 1–5.

email: i.chivers@kcl.ac.uk

© Ian D Chivers

Chapter 6
6.1.4

Arrays, Vectors and Valarrays in C++

80

Simple physics – voltage example Now consider a simple physics example. Here we go from -20 through +20 for the voltage. #include <iostream.h> int main() { // c1003 // in the f90 example we have a -20 < x < 20 // this is c++ 0 < x < 40 int voltage; float current[41]; float resistance; for ( voltage=0 ; voltage <= 40 ; ++voltage ) { resistance=voltage+10; current[voltage]=voltage/resistance; cout << voltage - 20 << " " << voltage << " " << resistance < " " << current[voltage] << "\n"; } return(0); } The solution to the problem in a programming language is now quite removed from the original problem. -20 through +20 has become 0 through 40. We are now having to do a few mental gymnastics to understand what is going on. The real world C++ -20 0 -19 1 -18 2 .. .. 0 20 .. .. +19 39 +20 40 Given the lack of array subscript checking in many C++ implementations this makes tracking down array indexing errors very difficult. Time Zone Example #include <iostream.h> int main() { int degree,strip; float t[361]; float v; for (degree=0 ; degree < 346 ; degree = degree+15) { v = (degree-180)/15.; for (strip=0 ; strip < 15 ; ++strip) { t[degree+strip] = v; cout << degree - 180 + strip << " "
6.1.5

© Ian D Chivers

email: i.chivers@kcl.ac.uk

81

Arrays, Vectors and Valarrays in C++
<< t[degree+strip] << "\n"; } } return(0);

Chapter 6

} Things have got worse. The real world has -180 through +180, C++ has 0 through 360. This conceptual gap is one of the reasons why raw C++ poses problems for array based numeric programming. We will look at ways of improving array handling in C++ using classes. Classes enable us to us array indexing based on the real world, and add error or subscript checking, to make our programs more reliable. Array Initialisation In this example we look at array initialisation. #include <iostream.h> int main() { int a[2][3]= { { 1,2,3 }, { 4,5,6 } }; for (int row=1;row<3;row++) { for (int column=1;column<4;column++) cout < a[row-1][column-1] < " "; cout < endl; } return(0); }
6.1.6

Whole Array Manipulation There is no whole array manipulation mechanism for old C style arrays. We can, through the use of classes and operator overloading, provide this functionality for one dimensional arrays, whilst still using the standard C++ array indexing notation, i.e. []. However it is not currently possible in C++ to overload [][], or [][][] etc. We will look into this area in greater detail in later chapters.
6.1.7

6.2

Vectors

The vector class was added to C++ to help overcome some of the deficiencies of raw C style arrays. The most important features of the vector class are:– it is an object; it is a container – it can hold objects of any type; subscript checking is available; the size is an integral part of the object;
6.2.1 Example 1 #include <iostream> #include <vector> using namespace std;

int main() email: i.chivers@kcl.ac.uk © Ian D Chivers

size(). return(0). A container is an object that can hold or contain other objects.Chapter 6 Arrays.average=0. cout << " Average is " << average.ac. average = sum/12.month<rainfall. We will look at the C++ concept of containers in more depth in later chapters. cout << " Type in the rainfall. 6. especially in the chapter on the Standard Template Library.month<rainfall.month<rainfall. What we have is a syntax that binds togethor data and an operation. The next thing of interest is:– vector<float> rainfall(12) . for (month=0.size() which in this case is 12. #include <iostream> #include <vector> using namespace std.2 cout << " Type in the rainfall.uk .chivers@kcl.++month) cin >> rainfall[month].++month) © Ian D Chivers email: i. for (month=0.month<rainfall. which declares rainfall to be a vector of size 12. Example 2 – subscript checking This example uses an alternate syntax that supports subscript checking. Vectors and Valarrays in C++ 82 { float sum=0.++month) cout << month << " " << rainfall[month] << " \n " .++month) cin >> rainfall. for (month=0. for (month=0. If this syntax looks a little strange at first don't worry.at(month). but now the size of the rainfall vector is an integral part of the object and available through rainfall. one per line \n" .month<rainfall. In this case the data is the rainfall vector and the operation (or function) is size().0.size().2. int month . and that it will hold numbers of type float. int month .++month) sum = sum + rainfall[month]. vector<float> rainfall(12) .size().size().month<rainfall. The next thing of interest is:– for (month=0.++month) This is a standard for loop. vector<float> rainfall(12) .0 .size().size().0 .average=0. one per line \n" .0. int main() { float sum=0. } The first thing of interest is:– #include <vector> which makes available the vector container. for (month=0.

++month) sum = sum + rainfall. We will look into this syntax later.2.ac. #include <iostream. average = sum/12.++month) sum = sum + rainfall. one per line \n" . cout << " Average is " << average. return(0). Example 4 – whole array assignment #include <iostream. for (month=0. average = sum/12.++month) cout << month << " " << rainfall.at(month) << " \n " .at(month).month<13.at(month). vector<float> rainfall(12) . } Note the meaningful error message if the index goes out of range.4 email: i.size(). 6.0. try { cout << " Type in the rainfall.uk © Ian D Chivers . } return(0).h> #include <vector> using namespace std.++month) cin >> rainfall.2. } catch (out_of_range) { cout << " index out of range " << month << endl.at(month). for (month=0.0 . } The syntax is rainfall.month<13.at(month) << " \n " .month<13.at(month). Example 3 – subscript checking with try/catch This example uses the exception handling facilities provided in C++ to trap the error and provide a meaningful error message. int month .h> 6. cout << " Average is " << average. for (month=0. Vectors and Valarrays in C++ Chapter 6 cout << month << " " << rainfall.3 int main() { float sum=0. We will look into this whole area in a later chapter.average=0. for (month=0.chivers@kcl.month<rainfall.83 Arrays. It will be much clearer after we have covered the chapters on classes.

++month) cin >> rainfall[month]. int main() { float sum=0. 6. for (month=0.0. and provide the high levels of performance often associated with Fortran code suites. average = sum/12. for (month=0.ac. int main() { float sum=0. } 6.t(12) .average=0. for (month=0.month<rainfall. for (month=0.++month) sum = sum + rainfall[month].size().0 . cout << " Average is " << average<< endl.uk .month<rainfall.month<rainfall.month<rainfall. one per line \n" .++month) cout << month << " " << rainfall[month] << " \n " .Chapter 6 Arrays. for (month=0. © Ian D Chivers email: i.size(). return(0). cout << " Type in the rainfall. one per line \n" .0 . for (month=0.month<rainfall.3.3 Valarrays C++ is used by people within the scientific community for numeric problems.size().size().average=0.0. t=rainfall.month<t. The valarray class has been added to C++ to enable a range of numeric problems to be more easily solved in C++.1 Example 1 #include <iostream> #include <valarray> using namespace std.++month) cout << t[month] << endl. int month . valarray<float> rainfall(12) .size(). We will look much more closely at this class in the chapter on the Standard Template Library. int month . vector<float> rainfall(12). cout << " Type in the rainfall. Vectors and Valarrays in C++ 84 #include <vector> using namespace std.++month) cin >> rainfall[month].chivers@kcl.size().++month) cout << month << " " << rainfall[month] << " \n " .

6.size().g. cout << " Average is " << average. x[i]. n/a no vector<float> x(10). The valarray class should be used when extremely high efficiency is required.chivers@kcl. and include:– machine oriented array dimensioning. vector declaration usage size email: i. Certain assumptions are made about valarray usage that permit high levels of optimisation.5 Summary lack of array bounds checking and this is a major problem as this is is one of the most common programming errors. There are some problems with C style arrays in C++.1.uk © Ian D Chivers .2 float x(10).85 Arrays. The three features of interest are:– the size of an array is now an integral part of the array object. x. x. Mixed language programming requires care therefore.6 6. 6. Chapter 6 } 6. Vectors and Valarrays in C++ for (month=0.++month) sum = sum + rainfall[month].1 Key Concepts Data Types 6.at(i). Some of the problems that occur with arrays in C++ go back to very early decisions made by Kernighan and Ritchie with C. return(0). we can use try/catch blocks to help in locating errors. rather than physical world array dimensioning.4 Array Element Ordering in C++ Arrays are ordered by row in C++. x[i]. e. average = sum/12. The vector class is a major advance for array handling in C++. we can achieve array subscript checking using the at() notation.month<rainfall. We will look at the technical aspects in a later chapter after we have looked at pointers and functions. and the vector class should be used in preference to the old C style array.ac. The problems that occur with the old C style arrays and pointer aliasing make high optimisation difficult in C++. 6.size(). unlike Fortran which orders by column.1 array declaration usage size subscript checking 6.1. stepping from 0–360 instead of -180–+180.6. We will also look at some of the other problems associated with arrays in raw C++.6.

x[i]. © Ian D Chivers email: i. 4.6. Try an array of size 10 in the first instance. Print out a table linking a person's name and weight. Then try 100.1.Chapter 6 subscript checking 6. Vectors and Valarrays in C++ yes valarray<float> x(10).000.1.uk . Is there a point at which the program won't compile or generates a run time error? Why do you think this is? Is this something that you would have expected from your experience with other languages? 3.000.000.7 Problems 1. What error messages do you get? What error options are there during compilation? 2. After successfully doing this modify the program to produce averages for each row and column as well.ac. Next try 10. Write a program that reads in a person's weight and a person's name. First try going beyond the end of the array when reading in data values.3 Arrays. Secondly try going beyond the end of the array when printing out the array.chivers@kcl. Modify each program to go outside of the array bound. Start with an array of size 1. Type in and run all of the examples in this chapter. no 86 valarray declaration usage size subscript checking 6. Allow 20 characters for the person's name. 1 2 3 4 5 6 7 8 9 Produce totals for each row and column. Write a program that will assign values to each element of an array and sum them.6. x.size(). Write a program to read the following data values into a 3*3 array.4 Associated control structure – for loop 6.

the for () statement the break. rather than try to ignore them. to introduce the switch statement with examples iterative statements:– while expression statement. continue and goto statement . Structured Programming. Dijkstra.7 Control Structures Summarising: as a slow-witted human being I have a very small head and I had better learn to live with it and to respect my limitations and give them full credit. do statement while expression. Edsger W. for the latter vain effort will be punished by failure. In particular:– logical expressions logical operators a block of statements several blocks of statements the if expression statement the if expression statement else statement. Aims The aims of this chapter are to introduce:– selection between various courses of action as part of the problem solution the concepts and statements in C++ needed to support the above.

1 If i is greater than 0 the cout statement is executed.4.2 Expression An expression is made up of one or more operations. i= " << i << endl. int main() { int i=0. 7.uk .Chapter 7 7 Control Structures Control Structures 88 There are a reasonable range of control structures in C++. int j=10.chivers@kcl. j= " << j << endl. 7.2 using namespace std. cout << " cout << " if (i=1) j=99. 7.1 Compound Statement or Block A compound statement or block of statements is a sequence of statements enclosed in {}. Thus what we have here is i=1 j=99 © Ian D Chivers email: i. Note that {} have to be used if it is necessary to execute multiple statements.4.ac. j= " << j << endl.3 Boolean Remember that within standard C++ boolean exists as a built in type and when we look at casting to an integer 0 is regarded as false and 1 is regarded as true. } i= " << i << endl. 7. Remember that = is an operator and that expressions return values. The evaluation of an expression typically means that one or more operations are carried out and a value is returned. If the expression is true execute the statement that follows. cout << " cout << " return(0). Example 2 #include <iostream> 7. A compound statement is treated as a single item and may appear anywhere that a single statement may occur. In this case a boolean value. We need to review a number of other concepts before looking at them in depth. This is probably not what was intended. Example 1 if ( i>0 ) cout << " Now greater than 0 " << endl. 7. Non zero values are also regarded as true through backwards compatibility ith C. They in turn are a mixture of operands and operators.4 if (expression) statement Simple if statement.

7.chivers@kcl. Example 2 if ( i < 0 ) cout << " Entering negative region" << endl. break. switch (i) { case 1 : cout << " one entered " << endl.uk © Ian D Chivers . break.89 Control Structures Chapter 7 This is not a C++ syntactic error.ac.5. cin >> i. else cout << " Calculating for positive i " << endl. } email: i. 7. Note the semi-colons. If you are familiar with Pascal or Ada this will catch you out. Again {} have to be used if it is necessary to execute multiple statements. cout << endl. else cout << " Positive region entered " << endl .1 switch (expression) statement This is best illustrated with a simple example. Example 1 if ( i < 0 ) cout << " Result not defined for negative values" << endl. 7.1 One or other of the cout statements will be executed.6. break.6 7. int main() { int i. else statement.2 or 3 entered " << endl. } // note no terminating semi-colon return(0). break. case 3 : cout << " three entered " << endl. default: cout << " number other than 1. else if ( i == 0 ) cout << " crossover reached " << endl. Standard extension to the if statement. 7. cout << " Type in an integer value " . case 2 : cout << " two entered " << endl. You asked for it and you got it.2 Note the semi-colons. Example 1 #include <iostream> using namespace std.5.5 if (expression) statement. Again will catch the Pascal/Modula 2 programmer out.

return(0). cin >> mark.1 using namespace std. i. else cout << " Item at position " << i << endl. It is a direct translation of the Fortran 90 example. ++i) cin >> a[i].ac. otherwise execution simply drops through! Equivalent to the case statement in other languages. © Ian D Chivers email: i.e.1 using namespace std. i=0.chivers@kcl. This example is the ex function taken from the Fortran 90 course. 7.0. i < end . the loop is always executed at least once as the test is at the end of the loop. etox=1.7 while (expression) statement Conventional while statement. i. int mark.7.e. int main() { float term. while (mark != a[i]) ++i. if (i == end ) cout << " Item not in list " << endl.8 do statement while (expression). const float tol=1.etox. statement may never be executed. Example 1 #include <iostream> 7. } We will look at the use of a sentinel in a later example. int main() { int a[11]. int nterm.Chapter 7 Control Structures 90 Note the use of the break statement to exit from the switch statement. for (i=0. Equivalent to repeat until statement. This example highlights both the if else statement and the while statement.uk . int end. a[end]=mark. Example 1 #include <iostream> 7.0E-6.x.8. 7. int i. cin >> end.

for ( i=0. expression 2 is evaluated after each loop and is generally used to modify the for loop control variable. Chapter 7 } 7. i < 10 . for ( i=0 . return(0). cout << endl. As long as this is true the for statement will be executed.expression 1. term = (x/nterm) * term. The following highlight this point– for (int i=0. int i. cout << " eotx = " << etox << endl. Some people love the ability to introduce variables in this way. Declare i and initialise to 0. This enables us to introduce for loop control variables at the time we set up the for loop. Note that {} must be used when multiple statements need to be executed.91 Control Structures term=1. for ( i=0 . i must have been declared prior to this statement.uk © Ian D Chivers . others hate it. expression 1 is the loop control mechanism. expression 2) statement Equivalent to the DO loop in Fortran or FOR loop in the Pascal family of languages.0.chivers@kcl. do { nterm+=1. int main() { float x[10]. cout << " Type in 10 numbers \n". etox+=term. cin >> x. email: i.ac. nterm=0.9. i < 10 . cout << " Numbers were \n ". } while (term > tol).1 using namespace std. i++) cin >> x[i]. Example 1 This complete program illustrates the above. It is the way it is. return(0). ini-statement may be declaration or an expression.9 for (init-statement. cout << endl. i++) cout << x[i] << " ". #include <iostream> 7.

10 break. Note however that you can only break from a single loop. We will however look at exception handling in a later chapter. continue.Chapter 7 } Example 2 #include <iostream> 7.6. If it is necessary to terminate an action within nested loops then the break won't do what we want. #include <iostream> using namespace std.uk . } What happens here? 7.i++) { if (j[i]>5) goto end. The following is a complete program that illustrates the use of all three statements. Control passes immediately to the appropriate depending on what type of loop we are in.chivers@kcl.i<10. break. end: cout << " j[i] now greater than 5 " << endl. The goto will allow us to jump to a labelled statement. we won't cover it at all.2 Control Structures 92 using namespace std. As the use of this statement is bad programming practice. continue.9}. The continue statement only makes sense with a loop.7.) cout << " Hello world \n " . } return(0).4. int j[]={0.1. } 7.ac. int main() { int i.9.8.5. return(0). int main() { for (.3. cout << i << " " << j[i] << endl. Type the program in and run it to see what happens. © Ian D Chivers email: i. goto statements The break statement can only occur within a switch or loop ( for.11 Summary C++ has a decent set of control structures. do or while). They provide us with most of the functionality we require. This is something that may not be fully implemented in the compiler you are using.2.. for (i=0.

4.13 Problems 1.. The physical world has many examples where processes require some threshold to be overcome before they begin operation: critical mass in nuclear reactions. Write a program to print out the 12 times table.uk © Ian D Chivers .3 7.9 A block of statements – { .4.12.. 3.4. 7.4.4.4. The middle column should be an integer and the columns to the left and right should be the corresponding pints and litre values.1 7.2 7. Output should be roughly of the form 1 * 12 = 12 2 * 12 = 24 2.12. The following problem tries to restrict the range of calculation.4 7. Write a program that produces a conversion table from litres to pints and vice versa.4 7. The new program should print out the length of the pendulum and period for lengths of the pendulum from 0 to 100 cm in steps of 0. If a cubic equation is expressed as email: i.4. a given slope to be exceeded before friction is overcome. Rewrite the program for the period of a pendulum..4. Unfortunately.12.} Control Statements the if expression statement the if expression statement else statement the switch statement while expression statement do statement while expression the for () statement break statement continue statement goto statement 7.12.12. This enables the middle column to be scanned quickly and the corresponding equivalent in litres or pints read easily.12.6 7..1 7.7 7. The output should comprise three columns.ac.4.3 7.12.5 7.chivers@kcl.12. whilst illustrating the possibilities of decision making.5 cm.12. and so on.12.12.12.2 logical and relational operators equal – == not equal – != less than – < less than or equal – <= greater than – > greater than or equal – >= not – ! and – && or – || 7.93 7. most of these sorts of calculations become rather complex and not really appropriate here.8 7.4.12 Key Concepts Control Structures Chapter 7 logical expressions An expression that evaluates to true or false.12. One litre is approximately 1 3/4 pints.

to ice. and the beach slope. and will calculate the energy required to raise (or lower) ice. What changes in wave type will be observed as the tide comes in? 6. the breaker wave height. many beaches have a concave profile. The beach slope may be taken as about 0. plunging and spilling. taxation at t3% on anything above. to determine the nature of the roots of a cubic from suitable input. the breakers are surging. If B is less than .chivers@kcl. this is termed progressive taxation. B. Assume that the specific heat capacity of ice and steam are identical to that of water. and wave periods of 10 to 15 seconds. (i) On the east coast of New Zealand. Hb (metres). the normal pattern of waves is swell waves. water or steam © Ian D Chivers email: i. You will have to make some realistic estimates of the tax thresholds mi and the taxation levels ti. taxation at t2% on the next m2 units. 8. q3 + r2 = 0. plunging breakers are observed. if B is greater than 0. The lower beach generally has a very low slope. the slope increases dramatically. the specific latent heat of fusion (ice/water) is 335 kJ kg–1. The form of breaking waves on beaches is a continuum. all roots real. You could use this sort of model to find out how sensitive revenue from taxation was in relation to cosmetic changes in thresholds and tax rates. m. say less than 1 degree (m=0.18). The specific heat capacity of water is 2009 J kg–1 K–1.018).Chapter 7 z3 and we let q and a 1 Control Structures a 2 94 z2 a 1 z a 0 0 9 3 ( a2 * a2 ) r ( a1 a2 3 a0 ) 6 ( a2 a2 a2 ) 27 we can determine the nature of the roots as follows: q3 + r2 > 0. one real root and a pair of complex.uk . For some reason. These may be classified empirically by reference to the wave period. with wave heights of 1 to 2 metres. the wave period is generally shorter. 3 to 5 metres. water or steam at the first temperature. 5. Write a program which will read in two temperatures. Write a generalised program to determine net income after tax deductions. all roots real. and between these values. q3 + r2 < 0. but for convenience we commonly recognise three major types: surging. Write out the gross income. the deductions and the net income. T (seconds). What changes occur in breaker characteristics as a storm builds up? (ii) Similarly.1. During storms.ac. taxation at t1% on the next m1 units. and at least two equal.068. These three variables are combined into a single parameter. to say 10 degrees or more (m=0. they are spilling. and the specific latent heat of vaporization (water/steam) is 2500 kJ kg–1. where B = Hb/(gmT2) g is the gravitational constant (981 cm sec–2).003. Incorporate this into a suitable program. and the wave heights higher. say 6 to 8 seconds. Personal taxation is usually structured in the following way:– no taxation on the first m0 units of income. but towards the high tide mark.

Hoare C.95 Control Structures Chapter 7 at the second. E. Dijkstra E. Prentice Hall. Knuth D.uk © Ian D Chivers .. in Current Trends in Programming Methodology. and dispells many of the myths concerning the use of the GOTO statement. Academic Press.ac.chivers@kcl. and its boiling point as 373 K. 1 BTU is 1055 J (approximately). 0o C is 273 K. One calorie is 4. Structured Programming. A. email: i.14 Bibliography Dahl O. Take the freezing point of water as 273 K. J. Structured Programming with GOTO Statements. This is the original text. R.. 1972. and for the truly atavistic. For those happier with Celsius. The quote at the start of the chapter by Dijkstra summarises beautifully our limitations when programming and the discipline we must have to successfully master programming.. Highly recommended. W. 7. Volume 1.. and a must. while 100o c is 373 K.1868 J. The chapter by Knuth provides a very succinct coverage of the arguments for the adoption of structured programming.

C. in the same way that a recursive procedure can call itself recursively from more than one place in its own body. A value of such a type would be permitted to contain more than one component that belongs to the same type as itself. Structured Programming Aims The primary aims of the chapter are:– to look at pointer syntax in C++ using the * operator.A.R.8 Pointers The question naturally arises whether the analogy can be extended to a data structure corresponding to recursive procedures. . to look at the associated address of operator &. Hoare. to look at the use of pointers and arrays.

This is the language that the underlying hardware – be it a pc.Chapter 8 8 Pointers Pointers 98 An understanding of pointers is essential for successful use of C++. The compiled program is then loaded into memory and executed. int* p_i. When we work with the executable program we then move to addresses.chivers@kcl.ac. actually uses. Parts of the compiled program are executable code. 8.1 Example 1: Basic Pointer Usage This is a simple example that introduces two of the fundamental operators in C++:– * or pointer to & or address of You have to type this program in.uk . When you look at the source of the program you think in terms of the variable name. } This program will give different results on different compilers even on the same platform. Macintosh or UNIX workstation. cout << " i " << i << endl. *p_i=1010. cout << " value of *p_i " << *p_i << endl. We will look in this chapter at some of the fundamentals of pointers and their usage in C++. Program Memory Memory Variable Address Contents i 0x0012FF7C 999 p_i 0x0012FF78 0x0012FF7C It is useful here to think about what happens when we compile a program and actually run it. The following is based on output from one of the compilers I use. After the compilation and link stage we end up with a file that contains what is called machine code. rather than variable names. // alter the value at the address p_i cout << i << endl. int main() { int i=999. other parts are data – our variables. #include <iostream> using namespace std. For each variable in our program there will be an area of memory set aside. cout << p_i << endl. Try it out on more than one platform. Thus each © Ian D Chivers email: i. cout << " value of &p_i " << &p_i << endl. compile it and run it to get a feel for what is happening. cout << &i << endl. cout << *p_i << endl. cout << " value of p_i " << p_i << endl. cout << " address of i " << &i << endl. p_i=&i. return(0).

Remember:– arrays of char are zero byte terminated. for (int i=0.99 Pointers Chapter 8 variable has an associated address in memory. This was a deliberate design decision in C by Kernighan and Ritchie. } sum=0. email: i.0. sum += x[i].*pstart. cout << sum << "\n". #include <iostream. Don't worry if this all appears baffling things will get clearer eventually! 8. cout << " Using &x[0] for start address \n". cout << i << " " << x[i] << " " << sum << "\n" . pend = pstart+10.2 Example 2: Arrays and Pointers This example looks at the use of pointers with arrays. cout << " Using x for start address \n". } This highlights quite clearly that if x is an array that x is nothing more in C++ terminology than the base address of the array. cout << " Standard array access notation \n". We will look into this whole area in far greater detail when we look at functions and arrays as function arguments in the next chapter.ac. } return(0). Serious usage of arrays in C++ is not possible without a very good understanding of pointers and pointer arithmetic. while (pstart < pend) { sum += *pstart++. The contents of this address are our actual data values. and that x is identical in meaning to &x[0].i<10. 8. cout << sum << "\n". pend = pstart+10. pstart = &x[0].uk © Ian D Chivers .h> int main() { float sum=0.0.0.3 Example 3: Pointers and Sentinels We looked earlier at an example that used a sentinel.*pend. In the following example we again use a sentinel. pstart = x. while (pstart < pend) { sum += *pstart++. } sum=0. This example looks at three ways of achieving the same result with a one dimensional array.x[10].++i) { x[i]=i.chivers@kcl.

© Ian D Chivers email: i. } We define line1 and line2 to be character arrays.0. double x=1. combing the use of sentinels.Chapter 8 Pointers 100 zero is classified as false in C++. cout << " address of z is " << &z << " value is " << z << " \n" < " using pointer to access the value of z " << *&z << endl. return(0). char* p2=line2. The above represents a very efficient way of copying a data structure. cout << line2 << endl.ac. cout << line1 << endl. and can't be used without a definition of what they point to. #include <iostream.4 Example 4: Indiscriminate Pointer Usage This example shows how one can use the two operators & and * quite indiscriminately in a C++ program.chivers@kcl.h> int main() { int i=1. ending at the zero byte at the end of the line. float z=1. while ( *p2++ = *p1++). char line2[80]. char* p1=line1. So when we hit the 0 byte terminating the string the expression ( *p2++ = *p1++ ) returns 0. the = is an operator Now consider the following program:– #include <iostream.uk . Remember that a boolean can be mapped onto integers and 0 is false. This will copy the contents of the line1 array to the line2 array. cout << " address of x is " << &x << " value is " << x << " \n" << " using pointer to access the value of x " << *&x << endl. You need to have a good understanding of operators and expressions in C++. The while loop is the major thing of interest in the program. Pointers are restrictive in Fortran 90. 8. and is false. C++ and C are hated and loved for permitting such terse expressions. cout << " Address of i is " << &i << " value of i is " << i << " \n " << " using pointer to access the value of i " << *&i << endl. We define p1 and p2 to be pointers to characters.0.h> int main() { char line1[]=" This is a line of text". Expressions like this are quite common in existing C and C++ code. pointers and C++ expression syntax.

As a crude yardstick the more error messages you get the better the compiler. *p1=&p2. c2=&c1. p1='\0'. c2=0.101 return(0). return(0). int *p_i=&i.6 8. } We will look at more realistic examples later in the course. compile and run it to see what happens.uk © Ian D Chivers .7 Problems To gain familiarity with the concepts of pointers in C++ try out all of the examples in this chapter.6. 8.chivers@kcl. p1=0. 8.2 Key Concepts * – pointer to & – address of int i=0. #include <iostream. c2=&'a'. c2='\0'. 8. p1 = " Mayhem". Will this program compile? What will happen if it does compile and you run it? Verify what you think by typing it in and compiling it.p2. If you have access to another system then try that system too.6. In later chapters we will look at more examples of pointer usage.3 arrays and pointers &x[0] when x is an array x 8. Pointers Chapter 8 } Type this program in.ac. Look at the following example.6. email: i. p1=p2. char c1.5 Summary This chapter has only introduced the concept of a pointer in C++.h int main() { int *p1. You need to get familiar with the address format for the system that you use.*c2.1 8.

look at the wide range of standard functions provided with C++. look at passing arrays as arguments to functions. but will they come when you do call for them? William Shakespeare. King Henry IV. . look at passing functions as arguments to functions. or so can any man. Why so can I. part 1 Aims The aims of this chapter are:– to to to to to to introduce with examples some of the predefined functions available in C++ introduce the concept of a user defined function. look at scope rules in C++ for variables and functions.9 Functions I can call spirits from the vasty deep.

h> in all of the examples so far. in C++ we have functions. #include <iostream.Chapter 9 9 Functions Functions 104 This is the major step forward in the ability to construct larger programs. in Fortran we have functions and subroutines. Have a look at math. Trigonometric function usage This example just uses the sine function from the maths library.h.h> #include <math.h. Every sub-program unit is a function.h> int main() { double z=1. 9.h.0. Find out where the header files are on the system you work on and print some of them out.0. string. Passing arguments of numeric type to standard maths functions We can also pass arguments of a variety of numeric types to the standard maths library functions. constant definitions and macros. 9. stddef. time. math. They either return a result of a particular type as in Fortran or carry out an action like a subroutine in Fortran.h and these are also available in C.h> #include <math.h. As C++ is backwards compatible with C we have access to all of the standard C header files.h. float x=1. cin >> x. stdlib.uk .1 This is identical to function usage in Fortran. We will look at how this is achieved later on. We have to have a way of breaking problems down into smaller sub-problems. Use of all library functions requires the inclusion of a header file.1. Let us look at some examples.h at least.1. We have already seen the use of <iostream.h. #include <iostream. stdio.h. The following are some of the standard header files:– ctype. float. Functions in C++ that carry out actions return a so called void result.h.1 Predefined Functions The predefined functions available in C++ are made available in groups and are provided in a standard library. cout << " Type in an angle \n". The terminology varies with programming languages. Where as in Fortran we distinguish between functions and subroutines we do not in C++.h. } 9.ac.chivers@kcl.h> int main() { float x.h and iostream. cout << " Sine of " << x << " is " << sin(x) << " \n ". which contains function prototypes. The basic idea is the same. int i=1. limits. return(0).h.2 © Ian D Chivers email: i. float. limits.

9.2 email: i. i. #include <iostream.3 cosh exp fabs floor tan fmod tanh frexp log log10 modf pow sin sinh sqrt and they are only a subset of those available in Fortran 90.13.3. Functions in <maths. but now we are using vectors. int nnn=20. cout << sum(b. This is an effective working technique for many problems. vector as argument This example is the same as the previous.8. return t.2 9.2. One d array as argument and one function This simple example looks at a summation function that adds up all of the elements of the array passed to it.i<n. int b[20]={1.chivers@kcl. } int main() { int a[10]={1.18. } C++ therefore supports numeric polymorphism.h> These are the functions in <maths.4. the interface int sum(int x[].17.nnn) << "\n".7.7.5.6.15.e.2. return(0).1 User Defined Functions We can define our own functions and this is quite straightforward.11. for (int i=0. One function.105 Functions Chapter 9 cout << " Sine of double is " << sin(z) << endl . return(0). int nn=10.h> int sum(int x[].19.uk © Ian D Chivers .int n) and actual body of executable code are all in one place. Note also the fact that we have the function sum as a whole.2.14.12. } Note the use of the array constructor to provide initial values.++i) t += x[i]. #include <iostream> #include <vector> 9.10.1.5.nn) << "\n".6. like Fortran.4.9.10}.16. cout << " Sine of int is " << sin(i) << endl . cout << sum(a.ac. cout << " Sine of float is " << sin(x) << endl .3.20}.2.8.int n) { int t=0.h>:– acos asin atan atan2 cos 9.9.

return(0).int n). for (int i=0.2.++i) cin >> a[i]. void readdata(int a[].size(). return (total). vector<int> b(20). return(s).++i) a[i]=i+1. return. } int sum(int a[].Chapter 9 using namespace std.int n). one d array as argument #include <iostream.i<n. } Note that there is no need to have a second argument as the size of the vector is an integral part of the vector object.++i) s+=a[i].i<n. void printdata(int a[].3 void readdata(int a[]. cout << sum(a) << endl.++i) total+=x[i]. } Functions 106 int main() { vector<int> a(10).i<a. for (i=0.size(). int i. } © Ian D Chivers email: i.int n) { int s.int n) { for (int i=0. int sum(int a[].uk .ac. int sum(vector<int> x) { int i. 3 functions.h> 9. for (i=0. for (i=0. cout << sum(b) << endl.int n). int total=0.i<b.++i) b[i]=i+1.size().i<x.chivers@kcl.

int n.n).++i) cout << a[i] << " ".i<n.107 Functions Chapter 9 void printdata(int a[].int n.int m). return(0).++i) email: i. for (int i=0. return.int m) { int s=0.int m) { for (int i=0.uk © Ian D Chivers .n). cout << endl. int sum(int a[][5]. int s=0.4 void readdata(int a[][5]. followed by the actual complete code later.ac.int n { for (int i=0. } Note that the array can be any size in this example. cout << " sum is " << s << endl.++j) a[i][j]=i+j. readdata(a. printdata(a. s=sum(a.j<m.int m).i<n.int n.n). } int sum(int a[][5].h> 9.int n. This is an effective coding style with larger programs.int n. int n=10.i<n. #include <iostream. main. return. Using 2d arrays as arguments This example looks at several functions.chivers@kcl. We have the interfaces to the three functions. } int main() { int a[10].2.++i) for (int j=0. void printdata(int a[][5].int m). each of which takes a 2 dimensional array as an argument. Note also that we have adopted an alternate coding style in this example. void readdata(int a[][5]. It's size is inherited from the calling routine.

++i) for (int j=0.int m).m).int n.h> 9. This aids in readability very considerably.int n. } Functions 108 void printdata(int a[][5].int n.++j) s+= a[i][j]. } int main() { int n=5.++j) cin >> *(a+m*i+j). return.uk . Passing 2d dynamic arrays as arguments We can pass a 2 d dynamic array as an argument but we now have to use pointer arithmetic to achieve what we want in the called routine. cout << " sum is " << s << endl. Note also that we define the interfaces for the functions first and then have the implementations later.m).n.5 void readdata(int* a.int m). #include <iostream.j<m.i<n. return(0).2. int m=5. } cout << endl.m).j<m. readdata(a. © Ian D Chivers email: i. } All array sizes apart from the first must be known at compile time.chivers@kcl. int s=0.ac. return(s).Chapter 9 for (int j=0.int m) { for (int i=0.int n. void printdata(int* a.++i) { for (int j=0.int m).int m) { for (int i=0.j<m. int a[5][5]. int sum(int* a.i<n. void readdata(int* a. printdata(a.n.n. cout << endl.int n.++j) cout << a[i][j] << " ". s=sum(a.

readdata(a_ptr.++j) cout << *(a+m*i+j) << " ".++i) for (int j=0.chivers@kcl.int m) { int s=0.109 return.uk © Ian D Chivers . cout << endl. } int main() { int n.int n. return(0).++i) for (int j=0.j<m. for (int i=0.n. Passing functions as arguments to other functions and procedure variables We will look at two ways of achieving this in the example below. } Functions Chapter 9 int sum(int* a.++j) s+=*(a+m*i+j). cout << " R and C ".j<m.m). int s=0.ac.m). cout << " sum is " << s << endl. int m. return.6 email: i. return(s). The first expression is very machine oriented and is one of the reasons that array handling in C++ is not straightforward when the number of dimensions is greater than one. } All we have is an area of memory that will hold m*n integer values.int m) { for (int i=0. The expression *(a+m*i+j) replaces a[i][j] as a two d array indexing mechanism.int n. int* a_ptr = new int [n*m] .h> 9.n.n. cin >> n >> m.i<n. printdata(a_ptr.i<n. cout << endl. s=sum(a_ptr.2. #include <iostream.m). } void printdata(int* a.

cout << " Using f1 . cout << f3(t. k<j .0/(i*i). © Ian D Chivers email: i. This looks strange. t=f1. The syntax is due to the precedence of the operators in C++. and quite frankly it is.0/i. return(0). In the second part we call f3 with t as the first argument and use the fact that a function name is equivalent to the address of the function. Don't worry you do get used to it. float f1(int i) { return 1. it just takes time.5) << endl. } float f2(int i) { return 1.5) << endl.uk . float f2(int i). return t. cout << " using t=f2 " << endl. } The thing of major interest is the way we declare the function f3.Chapter 9 float f1(int i). ++k) t+=(*f)(k).simple reciprocal " << endl. cout << f3(f2.int j).5) << endl.1/(i*i) " << endl. } int main() { float (*t)(int i). In the first part of the main program we call f3 with f1 and f2 as arguments. for (int k=1 .ac. cout << " using t=f1 " << endl. int j).chivers@kcl. This declares the first argument to the function to be a pointer to a function. } float f3(float (*f)(int i). cout << " Using f2 . cout << f3(f1. cout << f3(t. float f3(float (*f)(int i).int j) { float t=0. t=f2.5) << endl. Functions 110 float f3(float (*f)(int i).

j=t. } int main() { int i=1. int &j) { int t. Secondly we can qualify this by adding const. Let us look at a simple example of a function that swaps its two arguments and implement this in two ways.3 Function Arguments Functions Chapter 9 The default parameter passing mechanism in C++ is pass by value.3. t=i.j=2. It forces the calling routine to pass the address of the arguments. The default parameter passing mechanism for array arguments in C++ is to pass the base address of the array. #include <iostream.3. t=*p_i. a copy of the value of each argument is taken and the function works with that. cout < " i= " < i < " j= " < j < endl.&j). cout < " i= " < i < " j= " < j < endl. *p_i=*p_j.h> 9. #include <iostream.chivers@kcl. } Swapping arguments – passing by reference This example passes by reference. This avoids the copy. int* p_j) { int t. However this does mean that the function can now alter the parameters passed by reference. return(0). The calling routine just passes the arguments through. This should generate a compile time error.111 9. swap(&i. *p_j=t. } int main() { email: i.1 void swap(int* p_i. Firstly we can pass by reference. Swapping arguments – passing by address The first example passes the arguments using pointers. C++ provides two language features to help out here. i.2 void swap(int &i.uk © Ian D Chivers . No copy is involved.ac. This means that the function cannot alter the parameters passed as const and by reference.e.h> 9. i=j.

int* b.j=2. limits. cout < " i= " < i < " j= " < j < endl.chivers@kcl. csignal. cstdlib. swap(i. diagnostics library stdexcept. " << c << endl. Mayhem This example looks at the care that needs to be taken when mixing the various parameter passing methods. cout < " i= " < i < " j= " < j < endl. cfloat. cout << i << endl.uk . #include <iostream.&i. csdtarg. cout << a << " " << b << " *b=2. cwchar. new. strings library string. cstdlib. What is the value of i after calling the function f? 9.j). cout << a << " " << b << " } int main() { int i=0. localisation library The C++ standard defines a number of libraries.int c) { cout << a << " " << b << " a=1. memory.h> 9. cassert.3. " << c << endl.Chapter 9 Functions 112 int i=1. functional. cctype. You must run this program to see what is actually happening. and these include:– © Ian D Chivers email: i. cwctype. climits. f(i. return (0). cout << a << " " << b << " c=3.3 void f(int& a.ac. general utilities library utility. return(0). cstdlib. typeinfo.i).4 C++ Standard Functions language support library cstddef. } If you need to alter the arguments in a function then pass by reference. " << c << endl. exception. csetjmp. } " << c << endl. ctime. cstring. ctime. cerrno.

numeric. vector. 9. sstream.1 Key Concepts Predefined functions There are a large number of predefined functions available in C++. numerics library complex. Functions Chapter 9 containers library bitset. cwchar.chivers@kcl.4 email: i. algorithms library algorithm. 9. and you should have a look to see what has already been provided in the language before writing your own functions.4.6. 9. stack. set.4.uk © Ian D Chivers . iomanip. cstdlib.6 9.6. clocale. They are listed below. deque. ios. fstream. cstdio. The data in the called routine can be modified. cstdlib. ostream. Basic syntax type name(parameters) { executable code } 9. User Defined functions It is possible to define your own functions. iolibrary iosfwd.6.2 Array as parameter – base address used The default for array arguments. 9.2 interface and code body togethor interface and code body separate the second tends to be used when solving larger problems.6. istream. map. 9. There can be quite a performance overhead when passing large objects.ac.1 Pass by value – copy made This is the default for non-array arguments. streambuf. iostream. list.6. queue. valarray. We will look in later chapters at extending our knowledge after we have looked at classes. It is good sense to develop some familiarity with them to avoid unnecessary work. The only reliable source of information I've found here is the standard. There are two main programming styles for doing this.5 Summary We have only touched on some of what is possible in C++ in this chapter. This means that the original data in the calling routine can't be altered.113 locale.3 Parameter Passing There are a number of parameter passing methods in C++. 9. cmath. iterators library iterator. cstdlib.6.

4 Pass by const reference Now stop the called routine altering the data. but the copy is avoided. 9. 9.6.6.h to get more information about the standard maths functions available in C++.3 Functions 114 Pass by reference Now can alter the data in the called routine. Take care to ensure that you get the expression for calculating the position in the three d array correct. There are a few catches here. Write a program that prints out a table of values for sines. Are they identical to those in Fortran or Pascal? 3.4.4. cosines and tangents from 0 degrees to 90 degrees in 1 degree intervals. Modify the example that passes two d dynamic arrays (example 6) to work with three d arrays.Chapter 9 9. 5 and 6 d arrays? 4. Print out math.chivers@kcl. They are useful examples and can be used as sections of real programs. How long did it take you? Would you like to repeat this for 4.7 Problems 1.uk . 2. Try some of the examples out. © Ian D Chivers email: i.ac.

constructors and destructors. abstract data types. A. Hoare. without any knowledge of the value which a particular symbol might happen to have.10 Classes: User Defined Types Russell's theory of types leads to certain complexities in the foundations of mathematics. and that a check against violation of type constraints can be made purely by scanning the text. the C++ object model.. C. . Structured Programming. R.. Its interesting features for our purposes are that types are used to prevent certain erroneous expressions from being used in logical and mathematical formulae. It is said that Lisp programmers know that memory management is so important that it cannot be left to the users and C programmers know that memory management is so important that is cannot be left to the system anon Aims The aim of this chapter is to introduce the concepts and ideas involved in using the facilities offered in C++ for the construction and use of user defined types or classes:– concrete data types..

There are two stages in the process of creating and using our own data types. we must first define that type and second create variables of that type. d. Dates The examples we have covered far have looked at the intrinsic types available in C++. Functionality is provided by procedures that manipulate the data. In this chapter we look at the way we can add additional new types to a program. and extend the range of problems we can solve. #include <iostream> 10. We will then look at implementing the same data types using an abstract approach. A concrete data type is one where the user has to have an intimate knowledge of how the data type is implemented. later languages by abstract data types. d. Chivers.month << "/". Ellis Horwood. Consider the following example. Copies are in the college library.1 Concrete Data Types These examples are taken from the Fortran 90 material. I.Chapter 10 Classes – User Defined Data Types 116 10 Classes – User Defined Data Types User defined data types are an essential part of general purpose programming languages. The date of the Pascal Manual and Report is 1975.ac.D.year=1996. Similar examples in Pascal can be found in A Practical Introduction to Standard Pascal.month. cout << d. An abstract data type hides the implementation details from the user. © Ian D Chivers email: i.year << endl. If data hiding is required then abstract data types are the method of choice.uk .1 using namespace std. Modula 2 is a language that offered this and the first edition of Programming in Modula 2 is 1982.year. These are not new ideas! Both have their strong points. class date { public: int day.day=1. Early languages provided this functionality via concrete data types. We will look in the first instance at the implementation of a range of user defined types using a concrete data structure approach.day << "/". cout << d. Pascal is an early language to offer concrete data types. Classes provide a way of achieving both. cout << d.chivers@kcl. d. If high efficiency is required then concrete data types are the method of choice.month=1. 10. }. int main() { date d.1.

int main() { address a[2].name << endl. cin >> a[i]. cout << a[i]. i<2 . ++i) { cin >> a[i]. char postcode[9]. #include <iostream. cin >> a[i]. city and postcode.postcode. This is very similar to Fortran 90 and Pascal in syntax. In the main program we then create a variable which is an array of addresses. The following statements assign values to the components of d. We then create an array of addresses. for (int i=0 .chivers@kcl. In the above example we define a class of type date. } Classes – User Defined Data Types Chapter 10 New data types are defined in C++ using the class statement.2 class address { public : char name[41].street. }. email: i. cin >> a[i]. cout << a[i]. cin >> a[i]. } We here define the address data type to have components of name. char district[81]. i<2 .city. cout << a[i]. street. month and year.district << endl . and then print out their values. } return(0).city << endl . To make the components visible outside we use the public statement. all of type integer. We add one to the array length to allow for the string terminator in C++. Everything within a class is hidden or private by default. } for ( i=0 . Each of these is an array of characters. cout << a[i]. Addresses This example looks at an address data type.street << endl . In the main program we then define a variable d to be of type date. ++i) { cout << a[i].uk © Ian D Chivers .postcode << endl .district. char city[41]. char street[81].117 return(0).h> 10.name.1. district.ac. of varying lengths. day. This class has three component parts.

dob. Nested Data Types In this example we nest data types.district << endl. cout << p_details.add. }. cout << p_details.add.dob. char postcode[9]. cin >> p_details. cout << p_details.month << endl. cin >> p_details.year << endl. cin >> p_details.surname.district.dob.dob.dob. cin >> p_details.month.ac.dob.month.day << endl. address add. char district[81].chivers@kcl.h> 10.3 class address { public : char street[81].add.first_name << endl.Chapter 10 Classes – User Defined Data Types 118 Again this is similar to the Fortran 90 and Pascal syntax. class date_of_birth { public: int day.add.year. cin >> p_details. }. int main() { personal p_details. cin >> p_details. © Ian D Chivers email: i. cin >> p_details.street.street << endl. cin >> p_details.uk . date_of_birth dob. cout << p_details. cout << p_details. We then use these within the personal data type. cout << p_details. char city[41].first_name .1. cout << p_details. Here we have the two data types address and date of birth. cin >> p_details.postcode.surname << endl. class personal { public: char first_name[21].add.add. }. char surname[41].day.year.city. #include <iostream.

Run the program. */ while (cin >> c ) { /* Loop for all characters ptr = new (link). /* Start of list struct link *current.postcode << endl. cout << p_details. int main() { char c. } The syntax is very similar to Pascal and Fortran 90.h> #include <stdlib.4 struct link { char c. exit(1).chivers@kcl.119 Classes – User Defined Data Types Chapter 10 cout << p_details. } */ /* Add new value and clear subsequent link ptr->c = c. email: i. /* End of list */ struct link *ptr.city << endl.uk © Ian D Chivers .1.add.h> 10.4 . }.add. struct link *first = NULL.e.ac. */ /* Update pointers to add new value at end of list. ptr->next = NULL. */ /* The "if" statement could be omitted by making the */ /* first character entered a "special" case . /* Temporary */ /* /* /* /* /* */ Loop reading characters until the end of file */ character is reached (EOF) */ Note that one cannot use eof() to check for */ EOF until one has actually tried to read it */ . i. if (ptr == NULL) { cout << " Insufficient memory\n". spaces and end of lines? #include <iostream.but generality is a good idea! */ if (first == NULL) /* If this is the 1st character */ first = current = ptr.unlike Pascal.1. return(0).h> #include <stdio. struct link *next.as in */ /* Example 10. What do you notice about the white space characters. Reading user input using a singly linked list This program will eat up all input and terminate with a control z or end of file.

ac.Chapter 10 Classes – User Defined Data Types 120 else /* Otherwise. int main() { string s. current = ptr.. Let us look at this program in some depth to convince ourselves that it will work as we want. } cout << endl. Reading user input using C++ style strings The previous program read in all user input until and end of file was entered. } NULL is predefined within C++ and is used with pointers to terminate lists etc.h> 10. public: date(int. } Which is the easier to understand? 10. ptr = ptr->next.1 class date { int day.5 */ using namespace std. */ current->next = ptr.1. Dates #include <iostream. It then echoed the input back to the user.get(c) ) s+=c. We are now looking at data and methods applied to that data.2.int).chivers@kcl. What do you think the following program does? #include <iostream> #include <string> 10.year. These functions are called class member functions in C++ terminology.. while (ptr != NULL) { cout << ptr->c. char c. return 0. © Ian D Chivers email: i. while ( cin. } /* Now print out the list ptr = first.uk . cout << s << endl.month. return(0). Access to the objects is restricted to a set of functions.2 Abstract Data Types We look here at the same problems but now implement using an abstract data type approach.int.

date (a so called constructor) and print_date. Within the main program we define the variable d to be of type date. d=date(11.chivers@kcl. If we do supply three parameters then these values will set the values for day. d. month and year. The implementation of the date constructor and print_date function occur later. and use the constructor to provide an initial value. In this case date. We are now looking at binding together data and methods. A constructor is the C++ way of providing a data type with initial values. The next procedure print_date has no type associated with it and is therefore declared to be a function of type void. date::date(int d=0.int y=0) { day=d. email: i. } void date::print_date() { cout << day << "/" << month << "/" << year << endl. It will then print out the values of day. This means if we need to do anything with the date class that we have to use these two access mechanisms.1. If we don't supply any parameters when we define a variable to be of type date then initial values are provided of 0. return(0). To identify that the date procedure is part of the date class definition we preface the constructor name with the class name. }. This is a common C++ style where we do not want to clutter up the class definition with unnecessary baggage. It takes no arguments. in this case.uk © Ian D Chivers . We have two publicly visible components of this class. } int main() { date d(1. month and year respectively.print_date().ac. i.1996). } Let us look quite carefully here at the differences. only has definitions.1952).e. Note that day.print_date(). use date::date.2. Firstly within the class the three data components are no longer visible externally.0 and 0 for day.month=m. d. month and year have no visibility outside the date class.121 Classes – User Defined Data Types Chapter 10 void print_date(). month and year respectively.year=y. The class declaration. Everything within a class is private or hidden by default. The next thing we have are the actual implementations for the date constructor and print_date function.int m=0. It has the same name as the data type or class.

char s[]=" ". char street[81]. char d[]=" ".2 class address { char name[41]. The last statement prints out these new values.n). void set_address(). char street[].d).print_date statement invokes the print_date function with date values taken from the variable d. The next statement assigns a new value to d. Each of these would increase the security of any program that used this data type. If we wanted to check for valid dates then we could do so within the constructor. and it is much clearer as to what is actually happening.h> 10. strcpy(city. strcpy(district. #include <iostream. char district[81]. thirdly adding leap year checking. The d. Addresses This example is a conversion of the earlier example of addresses to use abstract data types. public : address (char name[]. char district[]. This is quite an improvement over the earlier concrete data structure example.c). }. © Ian D Chivers email: i. Some possibilities include:– firstly checking days to be in the range 1-31 and months in the range 1-12.2. void print_address().Chapter 10 Classes – User Defined Data Types 122 The next statement quite clearly highlights the way in which we are binding together data and methods.s). The main body of the program is greatly simplified. char c[]=" ". char city[]. char city[41].h> #include <string. char postcode[]).chivers@kcl. secondly checking day and month combinations. strcpy(street. We have hidden behind the constructor and print_date function all of the messy implementation details of the date data type. char p[]=" ") { strcpy(name.ac. address::address(char n[]=" ". char postcode[9].uk .

} In this example we have a constructor and two functions.print_address().print_address() . } void address::print_address() { cout << name << endl."SW2 5JB"). Within the main program we define a to be an array of type address. cout << district << endl. If arguments are supplied then we have to use the strcpy function in <string. cout << " city " .h> to set the corresponding internal variables. for (int i=0 ."Brixton". ++i) a[i]. email: i. } void address::set_address() { cout << " name " . a[0]=address( "Ian Chivers". ++i) a[i]. cin >> postcode. cout << street << endl.set_address(). for ( i=0 . We then initialise a[0]. i<2 . The set_address function prompts the use for values for the components of the address data type. cin >> district.chivers@kcl."21 Winterwell Road".ac. cout << " street " . The print_address function prints out the values of the address variable. i<2 . a[1]=address(). cout << " district " . The constructor will initialise variables of type address to be blank if no arguments are supplied to the constructor. cout << postcode << endl. cin >> city. cin >> name.123 Classes – User Defined Data Types Chapter 10 strcpy(postcode. for ( i=0 . } int main() { address a[2]. return(0).uk © Ian D Chivers . cin >> street. set_address and print_address. cout << city << endl. i<2 ."London". cout << " postcode " . ++i) a[i].p).

double r=0) { x_c=x. We then use the print_address function to print out these new values. z_c=z. sphere::sphere(double x=0.z_c. radius=r. }. We also look at the ways in which we can return objects of class types from functions. void set_centre(double.Chapter 10 Classes – User Defined Data Types 124 We then use the fact that if we don't supply arguments to the constructor we set each component value to blank. void get_centre(double &x.double y=0. void translate_by_pointer_sphere(sphere *p_s.y_c. double volume(void). radius=0.double r). y_c=0.radius.double z).double z. } sphere::sphere() { x_c=0. void set_radius(double).uk . We then have a simple for loop that invokes the print_address function with the array a.chivers@kcl. 10.double y.double y. sphere(). void translate_by_reference_sphere(sphere &s. We then use the set_address function to prompt the use for new values. #include <iostream.ac.h> #include <math. } void sphere::get_centre(double &x. void print_sphere().double).double z). private: double x_c.double z). y_c=y.double &y.h> class sphere { public: sphere(double x.3 Sphere class In this example we look at a sphere class.double &r). Again the main body of the program is greatly simplified. sphere translate_with_copy_sphere(double x.double. z_c=0.double y.double &y.double y.double x. Note we have a binding of data to a method. void get_radius(double &r).double x.double z=0.double &z) © Ian D Chivers email: i.

double y. cout << " radius = " << radius << endl. z_c=z.x_c=x_c+x. } double sphere::volume(void) { return 4. } sphere sphere::translate_with_copy_sphere(double x.double x. cout << " y = " << y_c << endl.uk © Ian D Chivers .125 { x=x_c.y_c=y_c+y.double z) email: i. new_s.ac. z=z_c. new_s.1419265358 * pow(radius. new_s.double y. } Classes – User Defined Data Types Chapter 10 void sphere::set_centre(double x.3).double z) { sphere new_s.0 / 3. } void sphere::translate_by_reference_sphere(sphere &s. y_c=y. return new_s. y=y_c.chivers@kcl.0 * 3.double z) { x_c=x.radius=radius. } void sphere::set_radius(double r) { radius=r. } void sphere::get_radius(double &r) { r=radius. } void sphere::print_sphere() { cout << " x = " << x_c << endl. cout << " z = " << z_c << endl.z_c=z_c+z. new_s.double y.

return 0. sphere s2(x2.z3=30.translate_with_copy_sphere(x1.y1. and these are called:– translate_with_copy_sphere translate_by_reference_sphere © Ian D Chivers email: i.r1=10.r1).z1.999. s.r2).double z) { pt_s->x_c=x_c+x. s3.z2.z1).r2=20.z1=10. sphere s1(x1.y3=30. s3.double y. double x3=30. sphere s3(x3.x_c=x_c+x. double x2=20. s3. pt_s->radius=radius. The second thing we have are four member functions that provide read/write access to the x. } void sphere::translate_by_pointer_sphere(sphere *pt_s. pt_s->y_c=y_c+y.999. s3=s0.translate_by_reference_sphere(s2.y.uk . This is just for ease of programming. pt_s->z_c=z_c+z.z_c=z_c+z. } The first thing we have are two constructors.y3. s2. The next member function calculates the volume of a sphere object.y1=10. s. s2.print_sphere(). We provide both a four argument constructor and a zero argument constructor.print_sphere(). s. s3.y1.print_sphere().radius=radius.double x.chivers@kcl.z3.r3=30.ac.print_sphere(). s0.print_sphere().999).99). s2.r3).print_sphere().translate_by_pointer_sphere(&s3.print_sphere(). } int main() { double x1=10.99.z2=20.99.z co-ordinates and radius of a sphere object.Chapter 10 { Classes – User Defined Data Types 126 s.y_c=y_c+y. sphere s0. s1.y2=20.y2. The next member function provides a way of printing information about the objects. Finally we have three member functions that provide ways of moving a sphere to a new position on the basis of the current position of another sphere object plus an additional x.z displacement.y.

999. 10. i.99) It is s2 that is being moved to a new position. double x.double z). Note also the syntax difference in the main program.3 Note the difference in the way we call this function. Why do we have the brackets round *pt_s? I guess that the -> was introduced to overcome this awkward syntax.y1.2 s0. translate_by_pointer_sphere(sphere *p_s. Note that new_s. Strictly speaking we could have written the following (*pt_s). It is the binding of the object with the procedure via late_with_copy_sphere that provides the linkage in this example.chivers@kcl. z_c and radius.translate_with_copy_sphere(x1.z1) 10. This means that the procedure directly modifies the contents of the object s passed through and there is no intermediate copy. There is no assignment in this case.double y. This means that the member function must create a new sphere object and then return that after generating the position.1 s0 is the current object and is referenced by x_c alone. i. i.x_c=x_c+x and this would have achieved the same effect.ac. Now we pass the object as a parameter on the member function. Note that in this example we are moving s3 to a new position. y_c. i.999.translate_by_pointer_sphere(&s3. translate_with_copy_sphere This uses the default parameter passing mechanism provided in C++.translate_by_reference_sphere(s2. Just to keep you on your toes! Note also the new syntax for accessing the component parts of the sphere object. translate_by_reference_sphere(sphere &s.e. double x.e. s3=s0.double y.uk © Ian D Chivers . s3.double z) Note the & – pass by reference.x_c and x_c refer to different objects.e. s2. pt_s->x_c=x_c+x where -> is regarded as a single lexical token in C++.999).127 Classes – User Defined Data Types Chapter 10 translate_by_pointer_sphere We will look at each in turn.3. setting the four variables x_c. Now we are passing the address of the object. Note the usage within the main program. 10.3. email: i.99. translate_by_pointer_sphere In this example we pass the parameter as a pointer to a sphere object.3.99.trans- translate_by_reference_sphere The other way of passing a parameter is by reference.e.

ac. strcpy(s1. cout << " Constructor " << &p << " " << ptr << endl. void f() { str s1(10).p. © Ian D Chivers email: i. cout << s1. str(int sz) { p=new char[size=sz] . } ~str() { cout << " Destructor " << p << " " << &p << " " << ptr << endl.h> 10. as a static object when the program starts and destroyed when the program ends. public : char* p.1 class str { void* ptr.4. delete[] p. An object can be created/destroyed:– automatically each time a section of code is entered and/or exited.Chapter 10 Classes – User Defined Data Types 128 10. #include <iostream. Constructor/Destructor Example 1 The following examples are all based on the old C style string class.p.2 for a more complete coverage of this). strcpy(s2. } }. as a member object – created as a member of another class or as an array element. str s2(20). The key point in the following examples are the problems that can occur when the class involves memory allocation and deallocation."abcdefghijklmnopqrs"). cout << " Address of s2 " << &s2 << endl.p << endl. i."abcdefghi").e. ptr=p .chivers@kcl. cout << " Address of s1 " << &s1 << endl. In both of these cases the object is an automatic object.uk . I've added an extra component to the class to enable us to see what is going on. as a free store object using new/delete.4 Constructors and Destructors It is necessary to look at what happens with classes when we use a class. what happens when objects are created and destroyed.h> #include <string. An object can also be constructed using an explicit constructor in an expression or as a temporary (see the standard r12. int size. There is the concept of a constructor and a destructor in C++ to handle this.

Not what was intended. We then assign values to the string component of this class. s1. As function f() terminates the destructor is called twice. with complex numbers.uk © Ian D Chivers . and these are:– delete cast-expression and delete [] cast-expression and the second form is used to delete arrays. We then make the objects the same by the use of the assignment statement. f(). } Classes – User Defined Data Types s2. " Address of s1 " << &s1 << endl. There are two forms of the delete operator. str(int sz) { p=new char[size=sz] . Incorrect usage of delete will result in memory loss. Note that there are valid reasons for the bitwise direct copy in the previous example.129 cout << s1=s2.h> #include <string. Constructor/Destructor Example 2 This example corrects the previous problem by overloading the assignment operator to achieve the desired effect.g. e.p << endl. We will look into this later. } email: i.chivers@kcl. ptr=p . public : char* p.4. return(0). cout << cout << cout << return. The snag is that we deallocate the same object twice. cout << " Constructor " << &p << " " << ptr << endl. cout << " program ends \n".ac. int size. Chapter 10 int main() { cout << " Program starts \n".p << " * " << s2. } In this example we construct two string objects. The effect of deleting an array with the first form is undefined and the effect of deleting an individual object with the second form is undefined. #include <iostream. The delete operator destroys an object created using the new operator. " Address of s2 " << &s2 << endl.h> 10.2 class str { void* ptr.p << endl.

strcpy(p. cout << " program ends \n". } void f() { str s1(10). cout << s2.p << endl. cout << " Address of s1 " << &s1 << endl. delete[] p.p << endl.size].p << " * " << s2.p. str& str::operator=(const str& a) { cout << " In the assignment operator \n". s1=s2.p. p=new char[size=a.a. strcpy(s2. cout << " Address of s2 " << &s2 << endl. if (this != &a) { delete[] p.p << endl. cout << s1.p)."abcdefghi"). str s2(20). } return *this. f(). Note also the check to make sure assigning something to itself. } int main() { cout << " Program starts \n".ac. strcpy(s1.chivers@kcl. cout << " Address of s1 " << &s1 << endl. cout << " Address of s2 " << &s2 << endl.uk .Chapter 10 Classes – User Defined Data Types 130 str& operator=(const str&). ~str() { cout << " Destructor " << &p << " " << ptr << endl. return(0)."abcdefghijklmnopqrs"). } }. return. © Ian D Chivers email: i. cout << s1. } Note in the function that overloads the assignment operator the use of this – the pointer to the current object.

#include <iostream. ~str() { cout << " Destructor " << &p << " " << ptr << endl.p).p << " * " << s2.uk © Ian D Chivers .p. cout << s1.131 Classes – User Defined Data Types Chapter 10 Note finally the use of strcpy to to the assignment.p << endl.ac. cout << " Address of s1 " << &s1 << endl. } { cout << " In the assignment operator \n".a.size]. str s2=s1. ptr=p . if (this != &a) { delete[] p. This one arise because of the difference between assignment and initialisation.chivers@kcl. strcpy(s1."abcdefghi"). int size. Constructor/Destructor Example 3 This example introduces another subtle error. cout << s2."jklmnopqrs").h> #include <string. strcpy(s2.h> 10.4.3 class str { void* ptr. } str& operator=(const str&). } void f() { str s1(10). str(int sz) { p=new char[size=sz] .p.p << endl. cout << " Address of s2 " << &s2 << endl. cout << s1. public : char* p. p=new char[size=a. cout << " Constructor " << &p << " " << ptr << endl.p << endl. strcpy(p. } return *this. email: i. delete[] p.

ptr=p . by the provision of what is called a copy constructor. int size. cout << " Address of s2 " << &s2 << endl. } str(const str&).4. } int main() { cout << " Program starts \n". str::str(const str& c) { © Ian D Chivers email: i. ~str() { cout << " Destructor " << &p << " " << ptr << endl. } The problem in this example occurs with string s2=s1 In this example the user defined assignment operator is NOT applied to an uninitialised object.Chapter 10 Classes – User Defined Data Types 132 cout << " Address of s1 " << &s1 << endl. str(int sz) { p=new char[size=sz] .h> #include <string. } }. return. return(0). This is reasonable as the pointer would contain a random value.uk .chivers@kcl.4 class str { void* ptr.ac. #include <iostream. delete[] p. f(). str& operator=(const str&). cout << " program ends \n". Constructor/Destructor Example 4 This example corrects the previous problem. public : char* p. cout << " Constructor " << &p << " " << ptr << endl.h> 10.

} void f() { str s1(10).chivers@kcl.p << endl.133 Classes – User Defined Data Types Chapter 10 cout << " copy constructor \n".p << endl. header is string& c) and the provision of a copy constructor overcomes the problem in the previous example. } str& str::operator=(const str& a) { cout << " In the assignment operator \n".c. << endl. strcpy(p.p). << endl. p=new char[size=a.4.ac.p. strcpy(p. if (this != &a) { delete[] p. str s2=s1. starts \n".size]. cout << " program return(0). } The copy constructor string::string(const 10."abcdefghi"). cout << s1. Constructor/Destructor Example 5 The following example highlights the sequence of events when calling functions with objects as arguments. The example looks at a variety of different ways of doing this to illustrate some of the flexibility (and complexity!) of C++.size]. email: i. cout << s2.p << " * " << s2.p."jklmnopqrs"). p=new char[size=c. } int main() { cout << " Program f().uk © Ian D Chivers . cout << " Address of s1 " << &s1 strcpy(s1. cout << " Address of s2 " << &s2 strcpy(s2.a.p << cout << " Address of s1 " << &s1 cout << " Address of s2 " << &s2 return. ends \n".p). << endl. cout << s1. endl. } return *this.5 << endl.

ac.i. }. i=c. } c(const c& c) { cout << " copy ctor ".i. } ~c() { cout << " dtor ". return *this.chivers@kcl. c add2(const c& c1. i=c. void c::print() { cout << i << " ".h> class c { private : int i.i).uk . } c& c::operator=(const c& c) { { cout << " = ". } c c::add1(const c& c1) { return c(i+c1.Chapter 10 Classes – User Defined Data Types 134 #include <iostream.const c& c2).} void print(). © Ian D Chivers email: i. i=ii. public : c(int ii) { cout << " ctor ". } void seti(int ii) { i=ii. c add1(const c& c).

135
}

Classes – User Defined Data Types

Chapter 10

c c::add2(const c& c1,const c& c2) { i=c1.i+c2.i; return *this; } c f1(const c& c) { cout << " f1 " ; return c; } c f2(c c) { cout << " f2 " ; return c; } int main() { c c1(1); c c2(2); c c3(3);cout << endl; c1.print(); c2.print(); c3.print();cout << endl; c2=c1; cout << endl; c1.print(); c2.print(); c3.print();cout << endl; c3=f1(c2); cout << endl; c1.print(); c2.print(); c3.print();cout << endl; c1.seti(10);c2.seti(20);c3.seti(30); c1.print(); c2.print(); c3.print();cout << endl; c3=f2(c2); cout << endl; c1.print(); c2.print(); c3.print();cout << endl; c1=c2.add1(c3); cout << endl; c1.print(); email: i.chivers@kcl.ac.uk © Ian D Chivers

Chapter 10

Classes – User Defined Data Types

136

c2.print(); c1.seti(100);c2.seti(200);c3.seti(300); c1.add2(c2,c3); cout << endl; c1.print(); c2.print(); c3.print();cout << endl; return (0); } You must run this example to see what is actually happening as we invoke the constructors and call a variety of functions. Constructor/Destructor Example 6 Now consider the following. Can you predict what the output of the program will be? #include <<iostream.h>> #include <<string.h>> class String { private: char *str; public: String() { cout << " In null constructor for String \n"; str=new char[30]; str[0]='\0'; } String(char *s) { cout << " In one parameter constructor for String\n"; strcpy(str=new char[strlen(s) +1],s); } ~String() { cout << " In destructor for class String\n"; delete str; } // other methods go here };
10.4.6

class A { private: String a1; public : A() { cout << " In null constructor fpr class A\n";} A(char *s) : a1(s) { cout << " In 1 parameter constructor for class A\n"; } © Ian D Chivers email: i.chivers@kcl.ac.uk

137
};

Classes – User Defined Data Types

Chapter 10

class B { private: A b1; public : B() { cout << " In null constructor fpr class B\n";} B(char *s) : b1(s) { cout << " In 1 parameter constructor for class B\n"; } }; class E { private : String e1; String e2; public : E() { cout << " In null constructor for class E\n";} E(char *str1,char *str2): e1(str1),e2(str2) { cout << " In 2 parameter constructor for class E\n";} }; class C : public B { private : String c1; public : C() { cout << " In null constructor for class C\n"; } C(char *str1,char *str2) : B(str1), c1(str2) { cout << " In 2 parameter constructor for class C\n"; } }; class D : public A { private : C d1; E d2; public : D() { cout << " In null constructor for class D\n";} D(char *str1,char *str2,char *str3,char *str4,char *str5) : A(str1),d1(str2,str3),d2(str4,str5) { cout << " In 5 parameter constructor for class D\n";} };

email: i.chivers@kcl.ac.uk

© Ian D Chivers

The other places the burden fairly and squarely on the user. //copy constructor A& operator=(const A&) //assignment ~A(). An object has a storage duration which influences its lifetime. i. It uses garbage collection.8 static memory for global variables. or by the implementation when needed.4. An object can have a name.7 It also pays to be very careful with parameter passing. and there is no dispose or deallocate statement in the language. 10.5 The C++ object Model – taken from the standard Section 1. © Ian D Chivers email: i. Constructor/Destructor Recommendations So for a class of any real complexity it is recommended that the following minimal set of constructors and destructors be defined:– class A { A(). An object has a type.6 of the standards states The constructs in a C++ program create.ac. the implementation generates information carried out in each object such that it makes it possible to determine that object's type during program execution. This obviously means that when we look at polymorphism there will be a run time overhead to determine the correct action during program execution. heap memory for objects referred to by pointers. C++ puts the onus on the user – caveat emptor.Chapter 10 Classes – User Defined Data Types 138 int main() { D obj1. access and manipulate objects. the meaning of the values found therein is determined by the type of the expressions used to access them. An object is a region of storage and except for it fields occupies one or more contiguous bytes of storage."three". The properties of an object are determined when the object is created. //simple constructor A(const A&).chivers@kcl. An object is created by a definition. Memory Allocation and Deallocation – Leakage and Garbage Collection There are typically three kinds of memory:– 10.e.4. Oberon 2 does not leak memory. 10. The object's type determines the number of bytes that the object occupies and the interpretation of its content. For other objects."five"). It is the third that normally causes problems. refer to. Some objects are polymorphic. by a new expression. One believes that the underlying system should take care of it – so called garbage collection behind the scenes. D obj2("one". memory is incorrectly deallocated and memory gradually leaks away. There are two schools of thought here.uk . } Run this example to see what happens. //destructor }. return(0). The term object type refers to the type with which the object is created."two". Using const and reference variables can help in avoiding the creation of temporary copies of objects."four". stack based memory for procedures and local variables. what method to invoke.

1.7.7. .7..2 10. and secondly using abstract data types where the internals are hidden from use and access is via procedures or member functions. One of them will definitely cause problems on non-DEC compilers.. 10.7. private: . 10.2.4 Constructors and Destructors Simple constructor Copy constructor Overload assignment operator Destructor A // simple constructor // copy constructor //assignment //destructor 10. .7. } Basic Class Syntax class name { public: .2.uk © Ian D Chivers . Try all of the examples in this chapter.3.3 10.3 10.1 Data public 10. We will be providing more information in later chapters.1 Abstract data types 10.3. We can do this in one of two ways.3..7.ac. Rewrite the linked list example as an abstract data type using classes.3..7. email: i.139 10. A(const A&) A& operator=(const A&). First using a concrete data structure approach where we need to have a good working knowledge of the internals of that data type. What errors occur? 2.7.8 Problems 1.1.1 Data Private 10.4 class { A().2 10. Please note that we have not covered all aspects of class usage in this chapter.6 Summary Classes – User Defined Data Types Chapter 10 Classes provide us with a way of implementing user defined data types.7 Key Concepts Concrete data types 10. If you have access to more than one compiler try out the constructor destructor examples on each of them.7. }. ~A().2 Functions public 10.chivers@kcl.7.7.2 Functions public 10.1 10.7.

Note that there is a reasonable amount of code involved in the leap year test. This is because these are two of the major languages used in introductory computer science degrees. implementation and verification of programs in an orderly and disciplined fashion – their words. Springer Verlag. Ada and C++ are increasingly taught in CS departments.e. Modula 2 sources are also widely available. the principles of software development as they relate to the specification.. Note that most of these are not written from the perspective of C++.9 Bibliography To gain some idea about user defined data types there is a list of books below that look at this whole area. and books looking at algorithms and data structures in these languages will become more widely available.ac. The book is very good for the complete beginner as the examples are very clearly laid out and well explained. i. checking the number of days in the other months.uk . A simple introduction to ISO/ANSI Pascal. Ladd Scott Robert. Sedgewick R.. This used Pascal.Chapter 10 Classes – User Defined Data Types 140 3. abstract data types and their implementation. Wiley. Pascal is probably the dominant language used in teaching about data structuring and algorithms. Bruell S. A Practical Introduction to Standard Pascal. Some of the data structures and algorithms used in this chapter are implemented in Pascal. 10.D. Contains examples on a floppy disk. Course CS2.. Addison Wesley. algorithms for sorting and searching. testing for a leap year if the month is February and taking the appropriate action for the number of days in February.M. August 1985. Chivers I. Ellis Horwood. 1983. arrays. There is a coverage of data structures.. Algorithms in C++. © Ian D Chivers email: i. Introducing Fortran 90. Advanced Programming and Problem Solving with Pascal. Modify the date example to add testing to ensure valid day month and year combinations. A C++ version of his original book Algorithms. As this course is aimed at people converting from Fortran 90 (as well as Pascal and other languages) examples used in that text are recast in C++ in this course. The book is aimed at computer science students and follows the curriculum guidelines laid down in Communications of the ACM. Chivers I.. Schneider G. M&T Books.. and integer arrays are taken from this source.D. C++ Components and Algorithms. Sleightholme J. Many numerical algorithm sources on the Internet are Fortran based.C. The case study examples based on ranges. but from the concepts of data structuring and algorithms. design.chivers@kcl..

Bertrand Russell.11 Templates A good notation has a subtlety and suggestiveness which at times make it seem almost like a live teacher. quicksort. Aims The aims of the chapter are to look at the template feature provided in C++ with two examples:– simple minimum. .

cout << " minimum for integer array is " << ii << endl. The function then takes the first element as the smallest and sequentially scans the rest of the array comparing each element in turn with the smallest. int ii=minimum(ia. ++i) if (array[i] < minimum_value) minimum_value = array[i]. int dsize = sizeof(da) /sizeof(double).7.0. int size) These two lines set up the function minimum to be a generic or polymorphic function. and then an array of reals.0. for (int i=1 .dsize). 11. template <class Type> Type minimum(Type array[]. This minimum function will work for any type where the < operator is defined. The function minimum returns a value of type Type.0.uk . If the new element is smaller they are swapped over and the scan continues. This means the ability to write an algorithm that can be used by data of a variety of types. © Ian D Chivers email: i. } The first thing to look at are the two lines at the start of this example.6.7. Other terminology used includes polymorphic functions. a minimum function.3. In this chapter we will look at defining and using our own templates. double da[]={10. The main program shows how the function is invoked with an array of integers. We will look at operator overloading in a later chapter.ac. template <class Type> Type minimum(Type array[]. int size) { Type minimum_value=array[0].6. i. i.1 Example 1 – Simple minimum This example looks for the minimum of the elements of an array.0. In a latter chapter we will look at the standard template library (STL) and what that has to offer. } #include <iostream.9. and takes two arguments.Chapter 11 11 Templates Templates 142 Templates provide the ability to do generic programming. cout << " minimum for real array is " << di << endl. i < size.5. swap function or sort function that works with data of any type.1.e.chivers@kcl. the first an array of type Type.1.2.5}.4.0. using a type as a parameter.4. int isize = sizeof(ia) /sizeof(int).0}.0. return minimum_value. the second an integer defining the size of the array.8.8.3.isize).2.0. double di=minimum(da.9. e.e.0. return(0).0.h> int main () { int ia[]={10.g.

} #include <iostream. } ended: .2 Example 2 – Hoare's Quicksort In this example we set up and use two generic functions using the template facility. The first swaps two elements in an array.j).i.3.h> int main() { double da[]={1.chivers@kcl.8. for (. int j) { Type tmp=array[i]. for (int ix=0. int j=r. int size=sizeof(da)/sizeof(double).0.3.5.6.10. template <class Type> void swap(Type array[].int size) { cout << " [ " .7. } template <class Type> void quicksort( Type array[].6.4.5}.6.143 Templates Chapter 11 11. print(da. int l.2. quicksort(da. array[i]=array[j]. j=j-1. while (v < array[j]) j=j-1.7.ix<size. The second is an implementation of Hoare's Quicksort.l.j).) { while (array[i] < v) i=i+1.9.5}.2. Type v=array[int((l+r)/2)].i. if (i<r) quicksort(array. array[j]=tmp.3.1.4.uk © Ian D Chivers . int ia[]={1.8.2.4. i=i+1 .size).9.5.8.7.size-1). if (i<=j) { swap(array.r).9. ++ix) cout << array[ix] << " ".5. cout << "] \n". } if (i>j) goto ended . int r) { int i=l. if (l<j) quicksort(array.ac.int i. cout << " Quicksort of double array is \n". email: i. } template <class Type> void print(Type array[]..

Basic Syntax Example template <class Type> Type minimum(Type array[].3 Other Issues The name of a template obeys the usual scope and access control rules. There are a number of sources in the bibliography that look into the algorithm in some depth. print(ia.4 Summary Most of the older texts don't contain any coverage of templates.uk . The body of the swap function is straightforward. Budd has a good coverage of how to use the STL. } The syntax for the definition of the generic functions is as in the first example. It is not appropriate here to go into a full coverage discussion of Quicksort. Look at the problem that you have to solve carefully. A member template shall not be virtual. for (int i=1 . This algorithm is based on Wirth's.5 Key Concepts The template mechanism provides a very powerful programming method. return(0). Chose the most appropriate way of solving it.5.Chapter 11 Templates 144 size=sizeof(ia)/sizeof(int). A local class shall not have a template member. 11.size). Compare this with the generic integer and real quicksort example from the Fortran 90 course.0. } 11. and is a translation of the Modula 2 example in Algorithms and Data Structures. It behaves quite respectably in a wide range of cases.chivers@kcl. return minimum_value.size-1). ++i) if (array[i] < minimum_value) minimum_value = array[i]. int size) { Type minimum_value=array[0]. cout << " Quicksort of integer array is \n". We look in this in more depth in later chapters. There are a number of improvements that can be made and will give a 20–30% improvement in running time. i < size. A template shall not have C linkage. Templates should be seen as a complement to the object oriented programming paradigm. 11.1 © Ian D Chivers email: i.ac. There is also pdf and postscript files on the web server with more information about the STL. quicksort(ia. 11. It allows us to write an algorithm once and have it work in a ploymorphic manner. Stroustrup has a good coverage of how to use templates. A destructor shall not be a template.

Do they work? Try using the other numeric data types available in C++. 2. Remember not all compilers fully support the standard.ac. Try using complex with the quicksort template example.145 11. email: i. Try both of these examples with the your compiler. You will need to look at the way in which your compiler actually offers support for the complex data type.6 Problems Templates Chapter 11 1.chivers@kcl.uk © Ian D Chivers .

' Humpty Dumpty said.' Lewis Carroll.' said Alice. commutative operators. Through the Looking Glass and What Alice found there. overloading () for two and higher dimensioned arrays. 'it means just what I choose it to mean . in a rather scornful tone. overloading << and >> for class i/o. 'whether you can make words mean so many different things. overloading [] for one dimensional arrays. . overloading binary operators.12 Operator and Function Overloading 'When I use a word.neither more nor less' 'The question is. Aims The aims are to introduce some of the rules and restrictions in C++ for successful use of operator and function overloading. smart pointers. in particular:– overloading unary operators.

e.ac.1. 12. An obvious example is in the previous chapter where using templates we saw how we could write one piece of code and have it work with several data types. The preprocessing symbols # and ## cannot be overloaded either. a reference to a class. write code that can be invoked whenever the comparison operator is used.1 Operator Overloading. There is some disagreement within the oo world over the necessity of operator overloading within an oo language. The basic idea is that for each operator we are interested in overloading we have a corresponding function that will be called to carry out the desired action. sequencing have predefined meanings when applied to class objects. For our data types we have to define our own meaning. an operator function shall either be a non-static member function or a non-member function and have at least one parameter whose type is a class. or number of operands of operators. we cannot introduce new operators.e. There are the following restrictions:– it is not possible to change the precedence. The following operators cannot be overloaded:– . For the built in types this is the case. This is called operator overloading.Chapter 12 Operator and Function Overloading 148 12 Operator and Function Overloading In this chapter we will look at operator and function overloading. . For the basic rules I've found Stroustrup to be the best source.1 © Ian D Chivers email: i. Let us consider unary and binary in turn.* :: ?: all of the others can be. Unary and Binary Operators The first thing we need to know are the rules that govern what we can and cannot do. ^ or ** for exponentiation because of historical accident the following operators: = assignment. 12.uk . grouping. The chapter in Meyer on genericity versus inheritance is well worth a read. Overloading is the ability to attach more than one meaning to an operator or name.chivers@kcl.g. in the sort example we again had to have a meaning attached to the comparison operator for each data type we wanted sorted. where we have the same name and multiple instances of constructors for a class. Note that not all oo languages support operator overloading. We have also seen examples of function overloading using classes. i. See the earlier chapter for a complete list and coverage of the operators available in C++. & address of and . an enumeration or a reference to an enumeration. In these examples the code would work providing the operations involved in the code segments were defined for the data types we were working with:– in the minimum example we obviously had to have a meaning to the comparison operator.

email: i.double i=0) { re=r.chivers@kcl.const complex &b). A global function is usually a friend.im=i. A binary operator may defined in one of two ways.ac.operator@(b) (a).h> 12. #include <iostream. Operator Overloading 1: + .b) operator@(a.const complex &b).operator@(0) As non-member function operator@(a) operator@(a.uk © Ian D Chivers .} complex &operator=(const complex &a). It means that we must use non-member functions with binary operators. Whilst there is a complex class in the standard it is very illuminating to look at the work involved in solving a numeric problem in C++. Let us look at some simple examples now. .1.operator->() (a).im. public: complex(double r. private: double re. = This example is based on the implementation of a complex arithmetic class in C++.operator=(b) (a).2 class complex { friend friend friend friend complex complex double double operator+(const complex &a. imag(const complex &a).operator[](b) (a). complex &operator=(double &a).149 Operator and Function Overloading Chapter 12 A unary operator can be defined in two ways. real(const complex &a). and this is shown below:– Expression @a a@b a=b a[b] a-> a@ As member function (a). and this some implications when we look at commutivity. firstly as a member function taking no arguments or as a global function taking one argument.. firstly as a member function with one argument or secondly as a global function taking two arguments.0) This is taken from table 8 in the draft standard. An operator function that is intended to be able to take a base type as the first argument cannot be a member function.operator@() (a). operator-(const complex &a. It is worthwhile noting that there is quite a remarkable syntactic difference between the above two approaches. This is illustrated in the example below.

re . © Ian D Chivers email: i. } int main() { complex x(0.1).im.b.re.2).im.chivers@kcl. a. inline double real(const complex &a) { return a.ac.re . } inline complex operator-(const complex &a .re + b.im).0). complex z(2.0.re . } inline double imag(const complex &a) { return a. a. complex y(1.im). } inline complex &complex::operator=(const complex &a) { re=a. im=a.im .im + b.re. } inline complex &complex::operator=(double &a) { re=a.uk . const complex &b) { return complex(a. const complex &b) { return complex(a. return *this. } void print(const complex &a) { cout << real(a) << " + i * " << imag(a) << endl. im=0. return *this.b.Chapter 12 Operator and Function Overloading 150 }. } inline complex operator+(const complex &a .

} complex &operator=(const complex &a). print(10-z). inline double complex::real(void) { return re.im. The print(10+z) would fail. Try the following program out. return(0). this is a syntactic issue. double imag(void). print(x+y). #include <iostream. print(z-x).h> class complex { private: double re.chivers@kcl. double real(void). complex operator-(const complex &b). complex &operator=(double &a). } Operator and Function Overloading Chapter 12 A number of things to note:– the binary addition operator is declared as a friend. It replaces all friend functions with member functions to highlight the points raised above. this is a syntactic issue. public: complex(double r. if we had declared the operator to be a member function then the program would not compile as subtraction as defined in this way is not commutative.151 print(x). the imag function is declared as a friend. print(10+z). print(z-10).double i=0) { re=r. }. print(y). } inline double complex::imag(void) { email: i. the real function is declared as a friend. print(z).uk © Ian D Chivers .im=i. The print(10-z) would fail. complex operator+(const complex &b). the binary subtraction operator is declared as a friend. if we had declared the operator to be a member function then the program would not compile as addition as defined in this way is not commutative. print(z+10).ac.

5). print(10-z). print(z). print(x). print(z+10). } int main() { complex x(1. print(y). print(z-x). } inline complex &complex::operator=(double &a) { re=a.1).ac. // comment out this line to compile print(z-10).re .re . // comment out this line to compile return(0).b. im=a.im). print(x+y). print(10+z). } void print(const complex &a) { cout << a.re.real() << " + i * " << a. return *this.imag() << endl. im=0. complex y(3.uk . return *this.b. complex z(5.3).im). im + b.im.chivers@kcl. } inline complex &complex::operator=(const complex &a) { re=a. } Operator and Function Overloading 152 inline complex complex::operator+(const complex &b) { return complex(re + b.0. } inline complex complex::operator-(const complex &b) { return complex(re . } © Ian D Chivers email: i. im .Chapter 12 return im.

exit(EXIT_FAILURE). Array bounds checking is also included. double &array::operator[](int i) { if (i<1 || i>5 ) { cout << " Error .h> class array { public: double &operator[](int i). for ( i=1.3 Operator and Function Overloading Chapter 12 Operator Overloading 2: [] This is a simple example to illustrate overloading the array subscripting mechanism of C++.h> 12.++i) x[i]=i*i.uk © Ian D Chivers . for ( i=1.1.153 12. } int main() { array x.index out of range \n".1. }. #include <iostream. int i.1.chivers@kcl. } Operator Overloading 3: () This simple example highlights the implementation of a two dimensional array. x[11]=1.h> #include <stdlib. private: double a[5]. } return a[i-1].ac. As a bonus we add array checking. with the use of () rather than [][] to achieve the array indexing.++i) cout << x[i] << " ". #include <iostream. return(0).i<=5.h> #include <stdlib.i<=5.4 class array { public: email: i.

++j) x(i.j) << " ". This can be done by overloading the << and >> operators. }.j. double &array::operator()(int i. x(11. #include <iostream.j<=5. } return a[i-1][j-1].h> #include <stdlib. private: double a[5][5]. for ( i=1.1.int j).ac.uk . The following example illustrates this.++j) cout << x(i.i<=5.++i) for ( j=1.j)=i*j. for ( i=1. } int main() { array x. private: double a[5][5]. exit(EXIT_FAILURE).i<=5. }. double &array::operator()(int i.chivers@kcl. return(0).6)=1.++i) for ( j=1. } Operator Overloading 4: << and >> It would be nice if we could use the C++ conventional operators for i/o.5 class array { public: double &operator()(int i.index out of range \n".j<=5.1.int j) { if (i<1 || j<1 || i>5 || j>5) { cout << " Error .int j).Chapter 12 Operator and Function Overloading 154 double &operator()(int i.int j) { © Ian D Chivers email: i. int i.h> 12.

for ( i=1. exit(EXIT_FAILURE).j<=5. If you do hit problems with operator overloading then I recommend three sources of information:– 12.j. cout << x. return(0).1.++i) for ( j=1. } ostream& operator<<(ostream& s . The function call mechanism should be used when the problem area doesn't lend itself easily to intelligible operator overloading. Operator overloading should be restricted to cases where its use is intuitive. I find this very useful. for ( i=1.chivers@kcl.155 Operator and Function Overloading Chapter 12 if (i<1 || j<1 || i>5 || j>5) { cout << " Error .j<=5.i<=5.++i) for ( j=1. } Guidelines for Operator Overloading There is the potential with operator overloading to write code that is incomprehensible.i<=5. } int main() { array x. When C++ is standardised then some of the dust should settle down. Quite a few gotchas in this area. Also try compiling with another compiler. Remember most compilers aren't standard conformant and many books can't possibly be bang up to date with the latest state of affairs.uk © Ian D Chivers . email: i. return s.++j) cout << x(i. chapter 10 of Seed's book.j)=i*j. array x) { int i. int i.j.++j) x(i. This is obviously the case with many mathematical problems.6 the chapter in Stroustrup on operator overloading. chapter 13 of the standard. } return a[i-1][j-1].index out of range \n".ac. This combined with the reference section at the back provide a lot of useful information.j) << " ".

the return types of the functions.Chapter 12 Operator and Function Overloading 156 12. Firstly if two functions differ only in the return type then this is an error. //ok no static g } Overload Resolution The standard states Overload resolution is a mechanism for selecting the best function to call given a list of expressions that are to be the arguments of the call and a set of candidate functions that can be called based on the context of the call. In this chapter we will look in a bit more depth at the whole idea. Secondly member functions can't be overloaded if one of them is static.int). void g() const. The following example from the standard illustrates this. how well (for non-static member functions) the object matches the implied object parameter and certain other properties of the candidate function.int. Certain function declarations can't be overloaded. how well the arguments match the types of the parameters of the candidate function. // ill formed void f() const volatile . 12. date(int. and there are examples of each given below. class x { static void f().2.2. void f() . no static g void g() const volatile . The selection criteria for the best function are the number of arguments. Exact Matching Argument matching can distinguish between constant and non-constant pointer and reference arguments. //ok. // ill formed void g().ac.2 Function Overloading You have already seen some examples of function overloading with the use of constructors.h> class date { public: date(int.2 © Ian D Chivers email: i. // ill formed void f() const . Matching is achieved in four ways. Quite a mouthful! At the simplest level we have:– 12.chivers@kcl.int). Consider the following date class with several constructors.uk . in the following order of precedence:– an exact match a match through promotion a match through standard conversion a match through user defined conversion. #include <iostream.1 the signatures of the functions.

int get_day(). int get_year(). day=d. } date::date(int d.uk © Ian D Chivers . day=d. date(). return 0. int get_month().month=m. } int date::get_month() { return 0.year=get_year().month=get_month(). date d3(25).year=get_year(). } date::date(int d) { cout << " in 1 parameter constructor " << endl.month=m. } int date::get_year() { return 0. } int main() { date d1(25.157 Operator and Function Overloading Chapter 12 date(int).year=y. email: i.12). date d2(25.month. day=d. date d4. } date::date() { cout << " in 0 parameter constructor " << endl. } date::date(int d.ac.int m. }.1996). private: int day. int date::get_day() { return 0.year=get_year(). day=get_day().chivers@kcl.year.int m) { cout << " in 2 parameter constructor " << endl.int y) { cout << " in 3 parameter constructor " << endl.12.month=get_month().

int).ac. date(int). #include <iostream.h> class date { public: date(int. Matching through Standard Conversion The following standard conversions are applied:– 12. a pointer of any type will match a formal argument of void*. int get_day(). zero will match both a formal argument of a pointer type and a formal argument of a numeric type. int date::get_day() { return 0.2. otherwise it is promoted to type unsigned int. void print_date().uk .chivers@kcl. } int date::get_month() { return 0. After these promotions have taken place exact matching is attempted with the newly promoted types. an argument of an enumeration is promoted to type int.year.4 any numeric type will match a formal argument of any other numeric type including unsigned.if the machine size of an int is larger than that of a short. © Ian D Chivers email: i.int). An argument of type unsigned short is promoted to type int. date(int. enumeration types will match a formal argument of numeric type. date().month. int get_month(). }. private: int day. Now consider the following example. Matching through promotion If there is no exact match promotions are applied in the following order:– 12. unsigned char or short is promoted to type int.int.2.Chapter 12 } Operator and Function Overloading 158 An examination of this program shows that we have an exact match between the variable definitions in the main program and the constructors. an argument of type float is promoted to type double. int get_year().3 an argument of type char.

} Think about this or a moment! Now run it to verify for yourself what is happening. } date::date(int d. return 0.int y) { cout << " in 3 parameter constructor " << endl. } date::date() { cout << " in 0 parameter constructor " << endl. } date::date(int d.month=m.int m) { cout << " in 2 parameter constructor " << endl.print_date(). d3.12. date d4.year=get_year(). date d3('c').print_date().month=get_month(). Matching through User Defined Conversion It is of course possible for you to write your own functions to achieve type conversion. day=d. day=d.159 Operator and Function Overloading Chapter 12 } int date::get_year() { return 0. d2. } void date::print_date() { cout << day << "/" << month << "/" << year << endl. } int main() { date d1('a'. 12. day=get_day().year=get_year().ac.chivers@kcl. } date::date(int d) { cout << " in 1 parameter constructor " << endl.int m. d4.print_date().month=m.month=get_month().9. date d2('b'.uk © Ian D Chivers .5 email: i.1996).12). day=d.year=y.2.year=get_year().print_date(). d1.

Function Overloading 12.2 Binary operators 12.4 Problems Try the examples out in this chapter.3.3.uk . All that is necessary is for the compiler to be able to determine which function you want to call.1 Functions distinguished by signature 12.3.3 Commutivity An operator that is intended to be able to take a base type as the first argument cannot be a member function. When designing a class it is good practice to define a number of constructors.2.2.3.6 Operator and Function Overloading 160 Guidelines for Function Overloading The key issue is differences in the function signatures.1 Unary operators 12. 12.3 Key Concepts Overloading is the ability to extend the meaning of a function or operator.2.3.3.2.1 12.2 Operator Overloading 12.ac.Chapter 12 12. 12. Look back at the date class to see what is meant here. to cover common usage.1.chivers@kcl. © Ian D Chivers email: i.

Steppenwolf. single inheritance. pure virtual functions.13 Virtual Functions For Madmen Only Hermann Hesse. Aims The aims of this chapter are to introduce some of the ideas involved in the use of virtual functions. . dynamic binding. In particular:– virtual functions. abstract data types.

year=y.year.int=0. and a function should be a pure function if we are interested in creating an abstract data type. It illustrates a number of C++ concepts including:– virtual functions. date::date(int d. } class world_date : public date { int day. public: world_date(int=0. the implementation of the function is type dependent.month=m. The first example looks simply at this issue. The date format in this example is European. and a function should be declared virtual if:– a class expects to be an object of derivation.uk . single inheritance. abstract data types.year=y. 13.1 Virtual Function Example 1 Consider the date class from chapter 10.Chapter 13 Virtual Functions and Abstract Data Types 162 13 Virtual Functions and Abstract Data Types Two concepts that are of major importance in oo programming are inheritance and dynamic binding.month. world_date::world_date(int d. }. } © Ian D Chivers email:i.int m. #include <iostream. Let us look at this now with an example. pure virtual functions.int=0. virtual void print_date() = 0.int m.month.ac.h> class date { int day.int y) { day=d.month=m.year. If we were in US then this would not work.chivers@kcl. dynamic binding. We have looked at classes and C++ supports inheritance through class derivation. Let's use this therefore as an example.int=0) . void print_date(). We now need to look at dynamic binding.int=0). }. public: date(int=0.int y) { day=d.

d1.int=0. the date constructor and a print_date function.print_date(). return(0). } class us_date : public date { int day.print_date().print_date(). It has two public functions.print_date(). }. us_date d3.1956).uk © Ian D Chivers . world_date d2(1.print_date(). d3.year. us_date d4(1. Note that the print_date function has been declared virtual.chivers@kcl. The whole of the interface can be examined in one place. } The first thing we have a the declaration of a base date class. This means that any class that inherits it MUST provide a function that will enable printing that variation of the date. } void us_date::print_date() { cout << month << "/" << day << "/" << year << endl. This class has three private variables. d2.print_date(). d3. email:i.year=y. As a means of documenting what we are doing it is useful to follow the convention of providing the arguments for the various functions of the class within the declaration. d4.1996). d1.1996).1.month=m.int d. } int main() { world_date d1.163 Virtual Functions and Abstract Data Types Chapter 13 void world_date::print_date() { cout << day << "/" << month << "/" << year << endl. day. us_date::us_date(int m. d1=world_date(1.int y) { day=d.month. void print_date().1. month and year.1956). public: us_date(int=0.3.ac.int=0). d3=us_date(1. without having to scan the rest of the code looking at the function bodies.3.

and therefore that date is an abstract class. A class with one or more pure virtual functions is an abstract class.y) .h> class shape { public: shape(int x. #include <iostream.y_ .int y. month and year. We set up for date variables. This defines the interface of the world_date class. 13. This means that it is a pure virtual function. d1 and d2 of type world_date and d3 and d4 of type us_date. Note that we have to define our private variables day. An abstract class means that we can provide an interface without providing any details of the implementation. Private variables cannot be inherited from a base class. } shape(const shape& s) : x_(s. This is a fundamental premise of information hiding. We then repeat the above for the us_date class.y_) {} }.2 Virtual Function Example 2 This example looks at a more complex example. We then have the executable part of the code.x_) .int length) : shape(x.} © Ian D Chivers email:i. protected: int x_.chivers@kcl. We have dynamic binding and the correct print_date function is invoked at the time the program runs. Constructors cannot be inherited from the base class. We then have the implementation of both the constructor and the print_date function. Note also that the print_date function provides a similar facility for printing in us date style.uk .Chapter 13 Virtual Functions and Abstract Data Types 164 Note also that the function print_date is made equal to zero. Finally we have the main program. The thing of interest here is the way in which we can write date. void operator=(const shape& s) { x_=s. and no objects of that class can be created.x_ . It also uses some of the alternate ways of doing things in C++ using constructors. and has a constructor and print_date function. It also uses the ubiquitous example from the graphics world of a shape. The next thing we have is a constructor for this base class.ac.y_. We now have a derived class world_date. y_(y) {} virtual ~shape() {} virtual void draw() =0. y_=s.print_date and it doesn't matter of what type date is. length_(length) {} void draw() { cout << " inside draw square " << endl. virtual void move() =0.int y) : x_(x) . class square : public shape { public: square(int x. This is based on the base class date. y_(s. Again it is derived from the base date class. Note also that we have both a constructor and a print_date function. Note that the constructor swaps over day and month to provide the us style of date.

100. move_and_repaint(r).} void move() { x_=10. initialisers for direct and virtual class subobjects and nonstatic data members can be specified by a ctor-initialiser.6.chivers@kcl. length_(length) . } protected: int length_.165 Virtual Functions and Abstract Data Types Chapter 13 void move() { x_=10. cout << " inside move square " << endl. mem-initialiser email:i.ac.int y.int length. } The first thing to note here is the new form of the constructor. } int main() { square s(50. cout << " inside move rectangle " << endl.10).20).10. s. }.50. int height_.move(). return (0). height_(height) {} void draw() { cout << " inside draw rectangle " << endl. move_and_repaint(s).int height) : shape(x. class rectangle : public shape { public: rectangle(int x.2) in the definition of a constructor for a class. void move_and_repaint(shape& s) { s. y_=10.y) . rectangle r(100. The standard states (section 12.draw(). } protected: int length_.uk © Ian D Chivers . y_=10. which has the form ctor: : mem-initialiser-list mem-initialiser-list: mem-initialiser mem-initialiser . }.

Both draw and move are implemented in a simple way just to illustrate what is actually happening.Chapter 13 Virtual Functions and Abstract Data Types 166 mem-initialiser: mem-initialiser-id ( expression-listopt ) mem-initialiser-id: ::opt nested-name-specifieropt class-name identifier What we have therefore is the use of the addition of : x_(x) . It helps to get around name conflicts. Dynamic binding takes care at run time of the problem of what move and draw functions to apply to the shape object.chivers@kcl.uk . What we can't do is to get old code to call new code.3 Summary Virtual functions and pure virtual functions provide us with the last of the tools that we need in C++ to write programs in an object oriented way. Thus protected is of considerable use when we are looking at inheritance. after the constructor and destructor. So what we have is an abstract data type shape. 13. A member of a class can be private. C. © Ian D Chivers email:i. squares and rectangles. This is time consuming and error prone. rather than private. Note also that whilst we can't make a constructor virtual we can make a destructor virtual. Note the use of the underscore character appended to the variable names. The clever thing now is that we can add at a later date further classes derived from shape and still use the move_and_repaint function without changing the source and recompiling. This is a common working practice in C++. without (typically) modifying the source and recompiling. Note also in this case the lack of a . Note that we also have a copy constructor. protected or public and if it is private it can only be used by member functions and friends of the class in which it is declared. It then applies move and draw to the object. if it is protected it can only be used by member functions and friends of the class in which it is declared plus by member functions and friends of classes derived fom this class. We then have the function move_and_repaint(). Note that in these classes we use a form of the constructor that calls the constructor for the base class. where we can build software where new code can call old code.ac. y_(y) {} to the constructor to enable us to initialise the x_ and y_ components of the class. Note here also the use of protected. Modula 2 and Fortran 90. Remember that a copy constructor for a class x is of the form x(x&). Compare this with the traditional programming approach using languages like Pascal. Inheritance is provided via classes and dynamic binding is provided by virtual functions. We overload the assignment operator in the conventional way. if it is public its name can be used by any function. We then have two derived classes. This takes an argument of type shape. In reality with a genuine graphics application there would be a lot more code! We essentially just move by 10 units in the x and y directions with move.

4.uk © Ian D Chivers . Add a new shape to the second example. email:i.5 Problems Try these examples out.4.ac.chivers@kcl. e.4.1 a class is expected to be an object of derivation the implementation is type dependent Pure Virtual Function A function should be declared a pure virtual function if we are interested in creating an abstract data type.2 Private Can only be used by member functions and friends 13. 13.4 Key Concepts Virtual function A function should be declared virtual if 13. 13.167 Virtual Functions and Abstract Data Types Chapter 13 13.5 Protected Can only be used by member functions.g.4 13. friends and friends of classes dervived from it. circles.4.4.3 13. Public Can be used by anyone.

Five Orange Pips. Aims The aim of this chapter is to look at a complete example of object oriented programming to bring together the concepts introduced in previous chapters. where he can get at it if he wants. Sir Arthur Conan Doyle. and the rest he can put away in the lumber room of his library.14 Complete OO Example A man should keep his brain attic stacked with all the furniture he is likely to use. .

inline int array::get_size(void) const { return n. array(const array &x). The base class in this example is an array class. virtual double &operator[](int index) const . class checked_array : public array { public: checked_array(int size) : array(size) {} double &operator[](int index) const. © Ian D Chivers email i.h> #include <stdlib.chivers@kcl. }. ~array() {delete [] pt. We then inherit this class and provide a range checked variant.Chapter 14 Complete OO Example 170 14 Complete OO Example This chapter looks at a complete example in C++ of simple inheritance. } inline double &checked_array::operator[](int index) const { check_bounds(index). double *pt.} array &operator=(const array &x). int get_size(void) const. #include <iostream. }.h> // needed for EXIT_SUCCESS #include <string.1 Range Checked Array A numeric example has been chose again.ac. private: void check_bounds(int index) const.uk . In reality use should be made of the vector and valarray classes in production code. protected: int n.h> // needed for memcpy() class array { public: array(int size). } inline double &array::operator[](int index) const { return pt[index-1]. The examples shows some of the work that needs to be done behind the scenes when actually using C++ to solve numeric problems. 14.

171 Complete OO Example Chapter 14 return array::operator[](index). exit(EXIT_FAILURE).x. if (pt==NULL) { cout << " array allocation failed \n". pt=new double[n]. return *this. } inline void checked_array::check_bounds(int index) const { if (index < 1 || index > n) { cout << " array index " << index << " out of bounds \n".n.int end) email i.n*sizeof(double)).x. n=x. exit(EXIT_FAILURE). } double sum(const array &a.pt. } memcpy(pt.n*sizeof(double)). } } array::array(int size) { n=size. pt=new double[n].pt. if (pt==NULL) { cout << " array allocation failed \n". pt=new double[n].uk © Ian D Chivers . if (pt == NULL) { cout << " array allocation failed \n". } } array::array(const array &x) { n=x. exit(EXIT_FAILURE). exit(EXIT_FAILURE).int start.ac. } array &array::operator=(const array &x) { delete [] pt. } memcpy(pt.chivers@kcl.n.

++i) cout << x[i] << " " << y[i] << endl.Chapter 14 { Complete OO Example 172 double result = a[start].0.1 14. int i=0. checked_array y=x.chivers@kcl. return (EXIT_SUCCESS).ac.i<=n. cout << " Sum of x[] is " << sum(x.1.n) << endl. return result. for (i=1. z=x.1. for ( i=1. } Notes 14.1 Class array two constructors one destructor overloaded assignment operator overloaded [] operator – virtual get_size function two protected variables array goes from 1 to n 14.0. for ( i=1.++i) cout << x[i] << endl.i<=n.i<=n. } int main() { const int n=10. array z(n/2). for (int i = start + 1 .1. i <= end .2 Class checked_array one constructor – calls constructor from base class © Ian D Chivers email i.1.n) << endl.++i) x[i]=i*i.1. ++i) result += a[i]. cout << " Sum of z[] is " << sum(z.uk . checked_array x(n).

Rumbaugh J. OO programming comes into its own with larger problems.2 Summary When writing programs to solve problems is is important to use an appropriate programming style. Prentice Hall. Addison Wesley. C++ supports programming using concrete data types programming using abstract data types object oriented programming generic programming Look at the problem that you have and choose whichever is best.3 Where do I go next? We have only touched on the surface.ac.uts. Looks at interfacing to both Lapack and Blas.. Nackman L. http://www. Springer Verlag. 2nd Edition. Stroustrup uses some of the built in types of C++ to illustrate oo programming.progsoc.html OO FAQ http://www. Run this example.B. Booch G.chivers@kcl. The C++ Programming Language. Benjamin Cummings. especially when we have to produce new versions to accomodate changing circumstances.uk © Ian D Chivers .com/objectcurrents/ 14. including both strings and complex.edu..cs. Seed G. etc. The OO Soapbox. An Introduction to OO programming in C++ with Applications in Computer Graphics. Addison Wesley. especially if you have some background in the database area. Blaha M. Scientific and Engineering C++.cyberdyne-object-sys. 1994. Worth a look at.rpi. as they don't cover the built in vector and valarray classes.R.com/oofaq2/ OO Currents http://www. An introduction with Advanced Techniques and Examples.. More information can be found in a number of sources. Could really do with an update to bring into line with the standard.173 Complete OO Example overloaded [] operator Chapter 14 14.sigs. The Seed case study is in ray tracing and takes up over 80 pages of the book. I've not been able to get of this edition but would imagine that it would be well worth a look given the 1st edition.au/~geldridg/cpp/ OO Fortran 90 http://www. They look at serious use of C++.edu/~szymansk/oof90.. 14. Stroustrup B. Barton J.. OO Design with Applications.. email i.. If you really do want to use C++ in the numeric area they have some good ideas. OO Modelling and Design.4 Problems 1.

ac.uk .Chapter 14 Complete OO Example 174 © Ian D Chivers email i.chivers@kcl.

In particular:– setting the width of the output field. Descartes.15 Files and I/O Common sense is the best distributed commodity in the world. picking up file names from command line arguments. for every man is convinced that he is well supplied with it. reading from files. writing to files. justification within a field. Aims The aims of this chapter are to look at the features in C++ that support files and I/O. . setting the precision for numeric output.

h> int main() { int i=123456789. cout << i << " " << f << " " << d cout. cout << i << " " << cout. 15.precision(15).23456789. float f=1. cout. cout << i << " " << cout.precision(15).2 Numeric i/o: setting justification #include <iostream. cout.width(10).ios::adjustfield).h> int main() { int i=123456789. << endl. " << d << endl. cout << i << " " << f << " " << d cout.uk .precision(10). cout.Chapter 15 15 Files and i/o Files and i/o 176 15.ac. } f << " f << " f << " " << d << endl.precision(10).23456789.width(15).width(10). cout << i << " " << cout.1 Numeric i/o: width and precision #include <iostream.width(15). cout << i << " " << f << " " << d cout. f << " " << d << endl.width(15).width(15). float f=1. cout. " << d << endl. << endl.23456789.chivers@kcl. cout << i << " " << return(0).23456789. double d=1. << endl.width(10). f << " " << d << endl. cout << i << " " << f << " " << d return(0).3 Numeric i/o: scientific notation #include <iostream. cout << i << " " << f << " " << d cout. } << endl. cout.width(10).setf(ios::left.h> © Ian D Chivers email: i. cout << i << " " << cout. 15. << endl. double d=1.

char* s2="") { cerr<< s1 << " " << s2 << endl. cout. cout.4 Numeric i/o: alternate number bases. exit(1). double d=1.uk © Ian D Chivers . return(0). ifstream in(argv[1]).argv[2]).h> void error(char* s1.h> int main() { int i=1024.precision(10).ac. ofstream out(argv[2]). cout << oct << i << endl.177 Files and i/o Chapter 15 int main() { int i=123456789.width(10). cout << i << endl. cout << hex << i << endl.chivers@kcl.setf(ios::scientific.23456789. cout << i << " " << f << " " << d << endl. email: i. float f=1.argv[1]). if (!in) error(" cannot open input file ". cout.. } int main(int argc. cout. } 15. cout << i << " " << f << " " << d << endl.5 File i/o: picking up the names from the command line #include <fstream.precision(15). return(0). cout.char* argv[]) { if (argc != 3) error(" Wrong number of arguments").ios::floatfield). octal and hexadecimal #include <iostream. cout << i << " " << f << " " << d << endl.width(15).23456789.width(15). } 15.width(10). cout << i << " " << f << " " << d << endl. if (!out) error(" cannot open output file". cout << i << " " << f << " " << d << endl. cout. cout.

uk .6 File i/o: hard coded file names in constructors #include <fstream. © Ian D Chivers email: i. ifstream in(i).get(c) ) out. while ( in. String o="o.put(c).ac. } 15.get(c) ) out.h> #include <string.7 File i/o: strings passed as arguments to constructors #include <fstream. while ( in.Chapter 15 Files and i/o 178 char c. If what you need isn't covered in these examples then try the Seed and Stroustrup books. ofstream out("o.chivers@kcl.8 Summary The examples here should be fairly self explanatory. } 15.put(c).dat").put(c).dat").dat". return (0).get(c) ) out. char c. ofstream out(o). while ( in. return (0). return (0). They have been chosen to provide examples of the most commonly asked questions. char c.h> int main() { ifstream in("i. } 15.dat".hxx> int main() { String i="i.

1 15.7. email: i.5 15.9.2 15.10Problems None! Just try some of the examples out.9.7 Files and i/o Chapter 15 Setting the width Setting the precision Justification Reading from files Writing to files Picking up files from the command line Alternate number bases for numeric output 15.7.1 octal 15.9.9.9.7.4 15.6 15.uk © Ian D Chivers .9 Key Concepts 15.ac.179 15.9.9.2 decimal 15.9.9.3 hexadecimal 15.9.chivers@kcl.3 15.

16 Errors and Exception Handling Don't interrupt me while I'm interrupting. Aims The aims of this chapter are look at errors and exceptions and the features in C++ that support exception handling. . Winston Churchill.

WHILE NOT EOF DO BEGIN NEW(Current@. the third in C++. the second in Fortran 90. Current:=Root. Current@.chivers@kcl. END. Let us look at examples in a couple of programming languages of reading user input. WHILE Current NIL DO BEGIN WRITE(Current@.Next:=NIL. © Ian D Chivers email: i. premature end of file: issue warning and terminate. VAR Root : Link.Next).C). Pascal and Modula 2 have the concept of EOLN and EOF. file not found: ask the user to retype the file name. numeric overflow: terminate the program with a warning. 16.1 Linked List – Pascal PROGRAM LinkedList(INPUT. READ(Root@. Next : Link. Current:=Root.ac.Chapter 16 Errors and Exception Handling 182 16 Errors and Exception Handling Let us look at some common errors and solutions:– invalid input: ask the user to retype the data values. TYPE Link = @ Node Node = RECORD C : CHAR. Current:=Current@. Current:=Current@.uk . Fortran 90 has the concept of implicit gotos via the END= and ERR= options and also the concept of IOSTAT returning a value to let you know something has gone wrong.Next). array out of bounds: terminate the program with an error message. Current : Link. BEGIN NEW(Root).C) END. The following are coding examples that read all input from a user until they type CTRL Z – end of file.Next END. numeric underflow: terminate the program with a warning. and you will all be familiar with one or more of these common errors. A common problem is that what is really quite simple code can be lost within the error handing code. READ(Current@. The examples also highlight the quite different ways that languages have in their handling of end of line and end of file. The first is in Pascal.C).OUTPUT).

ADVANCE='NO'.& IOSTAT=IO_Stat_Number) Current%C print *.chivers@kcl.3 Linked List – C++.h> email: i.io_stat_number IF (IO_Stat_Number == -1) THEN NULLIFY(Current%Next) ELSE ALLOCATE(Current%Next) ENDIF END DO print *.ADVANCE='NO'.h> #include <stdlib.uk © Ian D Chivers . Errors and Exception Handling Chapter 16 16. POINTER :: Next END TYPE Link TYPE (Link) . 'At start of input DO WHILE' Current=Root DO WHILE (ASSOCIATED(Current%Next)) Current=Current%Next READ (UNIT=*.183 END. POINTER :: Root .FMT=10.FMT=10. Current INTEGER :: IO_Stat_Number=0 ALLOCATE(Root) READ (UNIT=*. 'At end of input DO WHILE' print *.ac. 'At start of output DO WHILE' Current=Root DO WHILE (ASSOCIATED(Current%Next)) PRINT * .& IOSTAT=IO_Stat_Number) Root%C 10 FORMAT(A1) print *.2 Linked List – Fortran 90 PROGRAM C20_01 ! ! Simple linked list ! TYPE Link CHARACTER :: C TYPE (Link) .io_stat_number IF (IO_Stat_Number == -1) THEN NULLIFY(Root%Next) ELSE ALLOCATE(Root%Next) ENDIF print *. 'At end of output DO WHILE' END PROGRAM C20_01 16. Current%C Current=Current%Next END DO print *. old C syntax #include <iostream.h> #include <stdio.

*ptr. ptr->next = NULL. int main() { char c. */ current->next = ptr.but generality is a good idea! */ if (first == NULL) /* If this is the first character */ first = current = ptr. ptr = ptr->next. } /* Add new value and clear subsequent link ptr->c = c. else /* Otherwise. *current. */ /* Update pointers to add new value at end of list. } /* Now print out the list ptr = first. struct link }.1. /* /* /* Start of list End of list Temporary */ */ */ /* Loop reading characters entil the End Of File (EOF) */ /* Note that one cannot use eof() to check for EOF until*/ /* one has actually tried to read it . if (ptr == NULL) { cout << " Insufficient memory\n". current = ptr.unlike Pascal. exit(1).4 .chivers@kcl.as in Example 10. *first = NULL. struct link struct link struct link Errors and Exception Handling 184 *next.*/ while (cin >> c ) /* Loop for all characters */ { ptr = new (link). The "if" statement could be omitted by making the first character entered a "special" case . } © Ian D Chivers email: i.uk */ .ac.Chapter 16 struct link { char c. while (ptr != NULL) { cout << ptr-c.

email: i. else cout << " Number was " << i << endl. The concept of raising an exception and then passing control to an error handler is one that is now seen in a number of programming languages including C++. The Pascal code is probably the cleanest. Let us now look at using the exception handling features of C++ to come to our help here. cout << " Type in a number " . return 0. try { if ( i<0 ) throw j. int j=0. The facilities for handling errors and managing exceptional conditions has gradually improved in programming languages.185 cout << endl.ac. 16. Ada 95 and Java.h> int f(int i) { throw i.chivers@kcl.6 Example 2 – Exception raised in a function #include <iostream. } catch (int j) { cout << " Exception raised " << endl. cin >> i.uk © Ian D Chivers . } Errors and Exception Handling Chapter 16 16.h> int main() { int i=0. } 16. } return (0).5 Example 1 – Basic Syntax #include <iostream.4 Discussion It is apparent that the essential code is hidden to greater or lessor extent in the requirements to handle special conditions and the features provided by each language.

chivers@kcl. c=f(b). } return(0). } int f2(int i) throw() { if (i<0) throw i. } Errors and Exception Handling 186 catch (int i) { cout << " Exception raised and handled " << endl. int b=1. int c. } 16. return i.h> int f1(int i) throw(int . try { c=f(a). } int f3(int i) { © Ian D Chivers email: i.ac.Chapter 16 } int main() { int a=0. return i. if (i>0) throw (double)i. if (i>0) throw (double)i.uk .7 Example 3 – Function with Exception Specification The following example uses 3 functions to illustrate the variety of ways that we can use exception handling in C++. double) { if (i<0) throw i. #include <iostream.

f2(10). if (i>0) throw (double)i. You should see the following:– f1(-10) works f1(10) works f2(-10) fails f2(10) fails f3(-10) works f3(10) works There are extensions to this program set as a problem at the end of this chapter.187 Errors and Exception Handling Chapter 16 if (i<0) throw i. f2(-10). } catch (int i) { cout << " integer exception raised and handled " << endl. f3(-10). email: i. f3(10). } return(0).uk © Ian D Chivers . } int main() { try { f1(-10). return i.ac.chivers@kcl. f1(10). } The general form of the function header is:– return_type function_name (argument list) throw (type list) You will need to comment out the various function calls to verify what is happening here. } catch (double d) { cout << " double exception raised and handled " << endl.

Look aso for the xmsg and xalloc classes. unexpected() and set_unexpected. What happens? 2. 16.8 Example 5 – Exceptions and constructors and destructors.9.uk .Chapter 16 Errors and Exception Handling 188 16. It makes sense to look at throwing exceptions if there is the possibility of a constructor failing.10Problems 1. Look for terminate(). Locate the except.chivers@kcl.1 Basic Syntax try { . If any memory allocation is involved then the success or failure of the memory allocation should be determined and the appropriate action taken. © Ian D Chivers email: i.h header file and have a look at what is supported in the version of C++ that you use.. set_terminate().. } catch () 16.ac.9 Key Concepts 16. Modify the third example to throw a variable of type char from each functions.

S. . Aims The aims of this chapter are to provide a brief coverage of the facilities provided by the Standard Template Library. R. Peters. Ethics and Education.17 The Standard Template Library The good teacher is a guide who helps others dispense with his services.

I will be adding them as the year progresses. They are sufficient to allow us to solve quite a wide range of problems. list.ac. Our primary aim is to give a quick overview and make you aware of what is offered by the library.Chapter 17 The Standard Template Library 190 17 The Standard Template Library This chapter looks at the standard template library.2. Iterator – a mechanism that enables us to access and process all of the objects in a container. and David Musser at Rensselaer Polytechnic Institute. Stroustrup provides more information about people involved in specific parts of the STL. set. numeric Some basic terminology Container – an object that you can put something in. stack. The concept of generic programming has emerged as offering considerable advantages when solving certain kinds of problems. Don't reinvent the wheel! Containers – vector. 17. We can then use the iterators to traverse the list and identify the one we want. In C++ a class that holds objects of a particular type. vector Key Features include:– 17. bitset Iterators – iterator Algorithms – algorithm Strings – string Numerics – complex.1 17.2 Containers A range of containers are provided in the STL. queue.1 Library Organisation We are not going to cover the whole of the library in great depth.1 group of items of the same type selected or indexed by an integer key hence constant access time – O(1) higher level than arrays subscript checking possible size an integral part of the object © Ian D Chivers email: i. valarray. In reality some problems are well suited to a traditional procedural approach. deque. map. This library represents a major component of C++. Think of a telephone list. others are well suited to an oo approach and others well suited to a generic approach. We can use the list container in the C++ STL to hold the names and telephone numbers.uk . The STL is the outcome of many years of work by a number of people including Alex Stepanov and Meng Lee at Hewlett Packard.chivers@kcl. Pick the right tool for the job! There aren't many examples in this chapter at this time. 17.1.

191

The Standard Template Library
can be resized up or down – very inefficient compared to raw arrays if the size varies widely this carries a time penalty, can be O(n) in the worst case unsequenced

Chapter 17

list Key features include:–
17.2.2

group of items of the same type accessed by traversal – O(n) efficient data structure when the size varies widely has both a head and a tail Operations include:– erase(a) – remove element at a erase(first,last) – remove elements first to last clear() – remove all elements insert(a,b) – add b before a insert(a,n,b) – add n copies of b before a insert(a,first,last) – add elements first through last before p queue Key features include:–
17.2.3

first in first out data structure insert at back remove from front Operations include:– push_back() pop_back() push_front() pop_front() stack Key features include:–
17.2.4

last in first out data structure insert at front remove from front Operations include:– push_back() pop_back() push_front() pop_front()

email: i.chivers@kcl.ac.uk

© Ian D Chivers

Chapter 17
deque Key features include:–
17.2.5

The Standard Template Library

192

insert and remove from eithor end map, multimap Key features include:–
17.2.6

key and value data structure selected by key, but key isn't restricted to be an integer A simple example from every day life is a dictionary, where we index by words and the associated values are the meanings. One variant. set, bitset, multiset Key features of set include:–
17.2.7

group of items of the same type each item is unique unordered insertion, removal and testing can be done in O(log n) time Two variations are provided, bit set and multiset.

17.3 Iterators
One of the most commonly wanted operations with a container is to process all of the elements. The STL solves this problem by the provision of iteraters. begin() – Point to first element end() – Point to one past last element rbegin() – Points to first element of reverse sequence rend – Points to one past last element of reverse sequence

17.4 Miscellaneous Operations
The STL can be looked at in a variety of ways. Any classification scheme is in some sense arbitrary. size() empty() max_size() capacity() reserve() resize() max_size() swap() get_allocator() == != © Ian D Chivers email: i.chivers@kcl.ac.uk

193
<

The Standard Template Library

Chapter 17

17.5 Constructors
There are a small number of constructors. container() container(n) container(n,x) container(first,last) container(x) ~container()

17.6 Algorithms
The STL provides algorithms to solve many commonly ocurring problems. Don't reinvent the wheel! Non modifying sequence operations As the name says they don't modify the sequence.
17.6.1

for_each() find() find_if() find_first_of() adjacent_find() count() count_if() mismatch() equal() search() find_end() search_n() Modifying sequence operations Sequence is modified. Some thought needs to be taken here regarding perfomance. The cost of some of these operations may be quite large.
17.6.2

transform() copy() copy_backward() swap() iter_swap() swap_ranges() replace() replace_if()

email: i.chivers@kcl.ac.uk

© Ian D Chivers

4 includes() set_union() set_intersection() © Ian D Chivers email: i. 17.6.uk .chivers@kcl.6.Chapter 17 replace_copy() The Standard Template Library 194 replace_copy_if() fill() fill_n() generate() generate_n() remove() remove_if() remove_copy() remove_copy_if() unique() unique_copy() reverse() reverse_copy() rotate() rotae_copy() random_shuffle() Sorted sequences Don't forget that sorting is also provided elsewhere.3 sort() stable_sort() partial_sort() partial_sort_copy() nth_element() lower_bound() upper_bound() equal_range() binary_search() merge() inplace_merge() partition() stable_partition() Set algorithms Sets provide very elegant ways of solving certain problems.ac. 17.

Other header files to look at include:– <math. 17.6.7 next_permutation() prev_permutation() 17.uk © Ian D Chivers . The second provides the C++ fully blown string as object style. However for a variety of reasons both langauges are used in this area.195 The Standard Template Library set_difference() set_symmetric_difference() Chapter 17 Heap operations There are a small number of heap operations.6. Why waste time getting bugs out of a program when you can avoid them altogethor? Refer to the earlier chapter for more information.h> email: i.8 Numerics As Stroustrup says neither C or C++ were designed with numeric computation in mind.h> and <string> The first provides access to the old C style string as an array of char. The new standard provides facilities that make the language better at solving numeric problems. 17.h> <cmath> <limits. Many of the programming problems that occur with the old style strings just can't happen with the new style string. The <vector> container class overcomes many of the problems associated with the old C style arrays.6.6 min() max() min_element() max_element() lexicograhical_compare() Permutations Two functions. 17.ac.chivers@kcl.7 Strings The major headache here is the provision of two header files:– <string.5 make_heap() push_heap() pop_heap() sort_heap() Minimum and maximum Five functions provided. 17. You should use the new style whenever possible.

They are assumed to be alias free.h> <cfloat> <cstdlib> <numeric> complex Complex is now formally a part of C++. numeric Some very useful general algorithms are provided:– 17. If you have a background in numerical methods and some familiarity with Lapack.8.8. Blas and the NAG and IMSL libraries then I would recommend getting hold of Stroustrup and seeing what C++ can offer.3 accumlate() © Ian D Chivers email: i.ac.2 valarray The valarray template class was added to provide the high performance levels associated with Fortran in C++.8. 17.chivers@kcl. which is a major advance over old C style arrays. ctype ctype_byname deque front_insert_iterator gslice_array indirect_array insert_iterator istreambuf_iterator istream_iterator list map mask_array messages messages_byname moneypunct moneypunct_byname money_get money_put multimap multiset numeric_limits numpunct num_get num_put ostream_iterator 196 pointer_to_binary_function pointer_to_unary_function priority_queue queue raw_storage_iterator reverse_bidirectional_iterator reverse_iterator set slice_array stack time_get time_get_byname unary_negate valarray vector Complete Template Class List <climits> <float. Compiler writers are allowed to try all manor of optimisation techniques. The concept of a slice is important in matrix manipulation. It is provided for valarrays.Chapter 17 allocator auto_ptr back_insert_iterator basic_filebuf basic_ifstream basic_ios basic_isstringstream basic_ofstream basic_ostringstream basic_streambuf basic_string basic_stringbuf basic_negate binder1st binder2nd The Standard Template Library bitset codecvt codecvt_byname collate collate_byname complex. Masks are also supported.1 17. A slice is every nth element of a vector. valarray slice_array gslice_array mask_array indirect_array It is not possible to go into this area in any real depth.uk .

10Useful Sources ftp://ftp.orst. I will be putting examples up on the College web server.edu/pub/budd/stl/ReadMe. 17.ac.cs.chivers@kcl. 17. Use it.12Problems Try some of the examples out with the compiler you use. email: i.html 17. Don't reinvent the wheel. as the course progresses.9 Complete list of C++ template classes This was taken from table 12 of the standard. 17.11Summary The STL provides very good solutions to a wide range of frequently occuring problems.197 The Standard Template Library inner_product() partial_sum() Chapter 17 adjacent_difference() amongst others.uk © Ian D Chivers ..

' the Walrus said. . 'To talk of many things: of shoes–and ships–and sealing wax– of cabbages–and kings– And why the sea is boiling hot– And whether pigs have wings. Aims The aims of this chapter are to try and tie up the loose ends.' Lewis Carroll. Through the Looking Glass and What Alice Found There.18 Miscellanea 'The Time has come.

As was stated before it offers support for:– programming with concrete data types programming with abstract type types object oriented programming generic programming The vector and valarray classes help make it more suitable for numeric problems. I have tried where possible to compile and run all examples on a variety of platforms with as many C++ compilers as I have access to. It is also tough going. Look for the third edition for example of Stroustrup's book. As Stroustrup says C++ is a general purpose programming language.ac.Chapter 18 18 Miscellanea Miscellanea 200 The intention here is to tie up the loose ends and help put into perspective what has been covered in the notes and course. books written about C++ will be plain wrong. As stated elsewhere a PDF version is available and searchable on-line if you have an Acrobat reader installed. compilers will differ in their degree of standard conformance. its core application domain is systems programming in the broadest sense. Fortran 90 has much better support in this area. This creates a number of problems:– not every part of C++ has an totally clear meaning. If it requires facilities in C++ and not in Fortran (or whatever other language you know) then use C++. For numeric problems with two dimension arrays and above then C++ has some limitations in comparison to Fortran. You have also seen how to write your own array classes with subscript checking. 18.uk . However it is the definitive statement on C++. The valarray class allows aggressive optimisation and means that C++ can compete with Fortran in the high performance computing area. 18. The C syntax is a little strange at first but then what second and subsequent natural language isn't a little strange at first.chivers@kcl. The standard is on line. However it is big. If you don't have to pay for printing then you could consider printing it out. It is around 700 A4 pages. The key thing to remember is that you have a problem to solve. Seed is one of the more up to date texts. The vector class with its range checking is a massive step forward over old raw C style arrays.1 C++ as a Programming Language C++ is one of the C family of languages. I have tried in these notes to stick to what I believe to be standard C++. The other two are obviously C itself and Java. I would recommend very strongly looking at the FAQ's for up to date information on how to use C++. Its support for generic programming and object oriented programming is very good.2 The Standard Probably the major problem with C++ is that the standard was only finalised in November 1997. I would be very wary of older books on C++. It is therefore a powerful and complex language. However this is not without some cost in time and effort on your part. © Ian D Chivers email: ian.

3 implementation defined behaviour Behaviour. References are treated similarly.1 argument An expression in the comma separated list bounded by the parentheses in a function call expression.7 signature The signature of the function is the information about that function that participates in over load resolution: the types of its parameters and. Also know as an actual argument or actual parameter 18.3.201 18.3.0. 18. 18.0. If a pointer whose static type is pointer to class B is pointing to an object of class D.0. derived from B. the operand of throw. It depends only on the form of the program and does not change. 18.uk © Ian D Chivers . 18. The signature of a template function specialisation includes the types of its template arguments. to behaving during translation or program execution in a documented manner characteristic of the environment email: ian. or an expression in the comma separated list bounded by the angle brackets in a template instantiation. if the function is a non-static member of a class.3.2 dynamic type The dynamic type of an expression is determined by its current value and can change during the execution of a program.6 parameter An object or reference declared as part of a function declaration of definition in the catch clause of an exception handler that requires a value on entry to the function or handler.5 multibyte character A sequence of one or more bytes representing a member of the extended character set of either the source or execution environment. 18. Parameters are also known as formal arguments or formal parameters.0.3.0.3. Permissable undefined behaviour ranges from ignoring the situation completely with unpredictable results.4 implementation limits Restrictions imposed upon programs by the implementation.3. the CV qualifiers (if any) on the function itself and whether the function is a direct member of its class or inherited from a base class. for which the standard imposes no requirements.3. such as might arise upon use of an erroneous program construct or of erroneous data. a sequence of pre-processing tokens in the comma separated list bounded by the parentheses in a function like macro invocation. for a correct program construct and correct data.3.chivers@kcl.3.3 C++ Standard Definitions Miscellanea Chapter 18 The following terms are defined in the standard. the dynamic type of the pointer is pointer to D. The extended character set is a superset of the basic character set. or a template parameter. The range of possible behaviours is delineated by the standard. 18.0.0.0.ac. 18.8 static type the static type of an expression is the type resulting from analysis of the program without consideration of execution semantics. A function can be said to take arguments or to have parameters.9 undefined behaviour Behaviour. an identifier from the comma separated list bounded by the parentheses immediately following the macro name in a function like macro definition. 18. that depends on the implementation and that each implementation shall document.0.

and has an implementation defined set of libraries that includes certain language support libraries.ac. they are required to be diagnosed. A byte is at least large enough to contain any member of the basic execution character set and is composed of a contiguous sequence of bits.3. A freestanding implementation is one in which execution may take place without the benefit of an operating system. The least significant bit is the low order bit. Each byte has a unique address.5 of the standard states The fundamental storage unit in the C++ memory model is the byte. You have to get additional books on C++ and read them more than once.4 Coda These notes can't possibly be complete.Chapter 18 Miscellanea 202 (with or without a diagnostic message) to terminating a translation or execution (with the issue of a diagnostic message). 18.3.1 The C++ Memory Model.2 18. the most significant bit is the high order bit. For a hosted implementation. Good luck! 1 An implementation is free to disregard this requirement as long as doing so has no perceptible effect on the execution of the program. the number of which is implementation defined. taken from the standard Section 1. © Ian D Chivers email: ian.7. This is obviously of importance with embedded systems. I've tried to chose a subset of C++ that is sufficient to get you started. Note that many erroneous program constructs do not engender undefined behaviour. this standard defines the set of available libraries.1 18.4 of the standard states Two kinds of implementation are defined: hosted and freestanding.uk . The memory accessible C++ program is one or more contiguous sequence of bytes.chivers@kcl. C++ Implementation Options: Free vs Hosted Section 1.

Sign up to vote on this title
UsefulNot useful