Table Of Content++
Introduction to C for
Financial Engineers
An object-oriented approach
Daniel J. Duffy
++
Introduction to C for
Financial Engineers
ForothertitlesintheWileyFinanceSeries
pleaseseewww.wiley.com/finance
++
Introduction to C for
Financial Engineers
An object-oriented approach
Daniel J. Duffy
Copyright(cid:2)C 2006DanielJDuffy
Publishedby JohnWiley&SonsLtd,TheAtrium,SouthernGate,Chichester,
WestSussexPO198SQ,England
Telephone (+44)1243779777
Email(forordersandcustomerserviceenquiries):cs-books@wiley.co.uk
Visit our Home Page on www.wiley.com
AllRightsReserved.Nopartofthispublicationmaybereproduced,storedinaretrievalsystem
ortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,
scanningorotherwise,exceptunderthetermsoftheCopyright,DesignsandPatentsAct1988
orunderthetermsofalicenceissuedbytheCopyrightLicensingAgencyLtd,90Tottenham
CourtRoad,LondonW1T4LP,UK,withoutthepermissioninwritingofthePublisher.
RequeststothePublishershouldbeaddressedtothePermissionsDepartment,JohnWiley&
SonsLtd,TheAtrium,SouthernGate,Chichester,WestSussexPO198SQ,England,oremailed
topermreq@wiley.co.uk,orfaxedto(+44)1243770620.
Designationsusedbycompaniestodistinguishtheirproductsareoftenclaimedastrademarks.Allbrand
namesandproductnamesusedinthisbookaretradenames,servicemarks,trademarksorregistered
trademarksoftheirrespectiveowners.ThePublisherisnotassociatedwithanyproductorvendor
mentionedinthisbook.
Thispublicationisdesignedtoprovideaccurateandauthoritativeinformationinregardto
thesubjectmattercovered.ItissoldontheunderstandingthatthePublisherisnotengaged
inrenderingprofessionalservices.Ifprofessionaladviceorotherexpertassistanceis
required,theservicesofacompetentprofessionalshouldbesought.
OtherWileyEditorialOffices
JohnWiley&SonsInc.,111RiverStreet,Hoboken,NJ07030,USA
Jossey-Bass,989MarketStreet,SanFrancisco,CA94103-1741,USA
Wiley-VCHVerlagGmbH,Boschstr.12,D-69469Weinheim,Germany
JohnWiley&SonsAustraliaLtd,42McDougallStreet,Milton,Queensland4064,Australia
JohnWiley&Sons(Asia)PteLtd,2ClementiLoop#02-01,JinXingDistripark,Singapore129809
JohnWiley&SonsCanadaLtd,6045FreemontBlvd,Mississauga,ONT,L5R4J3,Canada
Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappears
inprintmaynotbeavailableinelectronicbooks.
LibraryofCongressCataloging-in-PublicationData
Duffy,DanielJ.
IntroductiontoC++forfinancialengineers:anobject-orientedapproach/DanielJDuffy.
p. cm.—(Wileyfinanceseries)
Includesbibliographicalreferencesandindex.
ISBN-13:978-0-470-01538-4(cloth:alk.paper)
ISBN-10:0-470-01538-1(cloth:alk.paper)
1.Financialengineering—Computerprograms. 2.C++(Computerprogram
language) I.Title.
HG176.7.D8432006
005.13(cid:3)3024332—dc22 2006020622
BritishLibraryCataloguinginPublicationData
AcataloguerecordforthisbookisavailablefromtheBritishLibrary
ISBN13 978-0-470-01538-4(HB)
ISBN10 0-470-01538-1(HB)
Typesetin10/12ptTimesbyTechBooks,NewDelhi,India
PrintedandboundinGreatBritainbyAntonyRoweLtd,Chippenham,Wiltshire
Thisbookisprintedonacid-freepaperresponsiblymanufacturedfromsustainableforestry
inwhichatleasttwotreesareplantedforeachoneusedforpaperproduction.
Contents
0 GoalsofthisBookandGlobalOverview 1
0.1 Whatisthisbook? 1
0.2 Whyhasthisbookbeenwritten? 1
0.3 Forwhomisthisbookintended? 2
0.4 WhyshouldIreadthisbook? 2
0.5 Thestructureofthisbook 2
0.6 Whatthisbookdoesnotcover 2
0.7 Moreinformationandsupport 3
PARTI C++ESSENTIALSKILLS 5
1 IntroductiontoC++andQuantitativeFinance 7
1.1 Introductionandobjectives 7
1.2 AshorthistoryofC++ 7
1.3 C++,amulti-paradigmlanguage 8
1.3.1 Object-orientedparadigm 8
1.3.2 Genericprogramming 10
1.3.3 Procedural,modularandfunctionalprogramming 11
1.4 C++andquantitativefinance:what’stherelationship? 11
1.5 Whatissoftwarequality? 11
1.6 Summaryandconclusions 13
1.7 Exercises 14
2 TheMechanicsofC++:fromSourceCodetoaRunningProgram 15
2.1 Introductionandobjectives 15
2.2 Thecompilationprocess 15
2.3 Headerfilesandsourcefiles 16
2.4 Creatingclassesandusingtheirobjects 19
2.5 Templateclassesandtemplatefunctions 22
2.6 Kindsoferrors 25
2.6.1 Compilererrors 25
2.6.2 Linkererrors 26
2.6.3 Run-timeerrors 26
2.7 Thestructconcept 27
vi Contents
2.8 Usefuldataconversionroutines 27
2.9 Summaryandconclusions 29
2.10 Exercisesandprojects 29
3 C++FundamentalsandMyFirstOptionClass 31
3.1 Introductionandobjectives 31
3.2 Class==memberdata+memberfunctions 32
3.3 Theheaderfile(functionprototypes) 33
3.4 Theclassbody(codefile) 35
3.5 Usingtheclass 38
3.6 Examiningtheclassindetail 40
3.6.1 Accessibilityissues 40
3.6.2 Usingstandardlibraries 40
3.6.3 Thescoperesolutionoperator‘::’ 41
3.6.4 Virtualdestructor:bettersafethansorry 41
3.7 Otherparadigms 41
3.8 Summaryandconclusions 45
3.9 Questions,exercisesandprojects 45
4 CreatingRobustClasses 49
4.1 Introductionandobjectives 49
4.2 Callbyreferenceandcallbyvalue 49
4.3 Constantobjectseverywhere 52
4.3.1 Read-only(const)memberfunctions 52
4.4 Constructorsindetail 54
4.4.1 Memberinitialisation 55
4.5 Staticmemberdataandstaticmemberfunctions 55
4.6 Functionoverloading 57
4.7 Non-memberfunctions 58
4.8 Performancetipsandguidelines 58
4.8.1 The‘inline’keyword 58
4.8.2 Anonymousobjectsinfunctioncode 59
4.8.3 Loopoptimisation 60
4.9 Summaryandconclusions 60
4.10 Questions,exercisesandprojects 60
5 OperatorOverloadinginC++ 63
5.1 Introductionandobjectives 63
5.2 Whatisoperatoroverloadingandwhatarethepossibilities? 63
5.3 Whyuseoperatoroverloading?Theadvantages 65
5.4 Operatoroverloading:thesteps 68
5.4.1 Aspecialcase:theassignmentoperator 70
5.5 UsingoperatoroverloadingforsimpleI/O 71
5.6 Friendfunctionsingeneral 72
5.6.1 Friendclasses 73
5.7 Summaryandconclusions 74
5.8 Exercise 74
Appendix:usefuldatastructuresinC++ 75
Contents vii
6 MemoryManagementinC++ 79
6.1 Introductionandobjectives 79
6.2 Singleobjectsandarraysofobjectsonthestack 79
6.3 Specialoperators:‘new’and‘delete’ 82
6.3.1 Singleobjects 82
6.3.2 Arraysofobjects 83
6.4 Smallapplication:workingwithcomplexnumbers 84
6.5 Creatinganarrayclass 86
6.5.1 Memoryallocationanddeallocation 86
6.5.2 Accessingfunctions 87
6.5.3 Examples 88
6.5.4 Thefullheaderfile 88
6.6 Summaryandconclusions 89
6.7 Exercises 89
6.8 Reviewquestionsandcomments 91
7 Functions,NamespacesandIntroductiontoInheritance 93
7.1 Introductionandobjectives 93
7.2 Functionsandfunctionpointers 93
7.2.1 Functionsinfinancialengineering 94
7.2.2 Functioncategories 94
7.2.3 ModellingfunctionsinC++ 95
7.2.4 Applicationareasforfunctionpointers,partI 96
7.3 AnintroductiontonamespacesinC++ 96
7.3.1 Someextrafunctionality 97
7.4 AnintroductiontotheinheritancemechanisminC++ 99
7.4.1 Basicinheritancestructure 99
7.4.2 Addingnewfunctionality 101
7.4.3 Overridingfunctionality:polymorphicand
non-polymorphicbehaviour 102
7.5 Multipleinheritance 104
7.6 Solutionofnonlinearequations 104
7.7 NonlinearsolversinC++:designandimplementation 106
7.8 Applyingnonlinearsolvers:calculatingvolatility 108
7.9 Summaryandconclusions 109
7.10 Exercisesandprojects 109
8 AdvancedInheritanceandPayoffClassHierarchies 113
8.1 Introductionandobjectives 113
8.2 Thevirtualspecifierandmemorydeallocation 113
8.3 Abstractandconcreteclasses 115
8.3.1 Usingpayoffclasses 118
8.4 Lightweightpayoffclasses 119
8.5 Superlightweightpayofffunctions 121
8.6 Thedangersofinheritance:acounterexample 123
8.7 Implementationinheritanceandfragilebaseclassproblem 127
8.7.1 Deephierarchies 127
8.7.2 Multipleinheritanceproblems 127
Description:This book introduces the reader to the C++ programming language and how to use it to write applications in quantitative finance (QF) and related areas. No previous knowledge of C or C++ is required. - experience with VBA, Matlab or other programming language is sufficient. The book adopts an increme