microsoft visual c++

542

Upload: rajivparaj

Post on 14-Sep-2015

69 views

Category:

Documents


13 download

DESCRIPTION

Microsoft Visual C++

TRANSCRIPT

  • Microsoft Visual C++/CLI Step by Step

    Julian Templeman

  • Pub shed w th the author zat on of M crosoft Corporat on byORe y Med a, Inc1005 Gravenste n H ghway NorthSebastopo , Ca forn a 95472

    Copyr ght 2013 by Ju an Temp emanA r ghts reserved No part of the contents of th s book may be reproduced or transm tted n any form or by any means w thout the wr tten perm ss on of the pub sher

    ISBN 978-0-7356-7517-9

    1 2 3 4 5 6 7 8 9 LSI 8 7 6 5 4 3

    Pr nted and bound n the Un ted States of Amer ca

    M crosoft Press books are ava ab e through bookse ers and d str butors wor dw de If you need support re ated to th s book, ema M crosoft Press Book Support at msp nput@m crosoft com P ease te us what you th nk of th s book at http://www.microsoft.com/learning/booksurvey

    M crosoft and the trademarks sted at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the M crosoft group of compan es A other marks are property of the r respect ve owners

    The examp e compan es, organ zat ons, products, doma n names, ema addresses, ogos, peop e, p aces, and events dep cted here n are fict t ous No assoc at on w th any rea company, organ zat on, product, doma n name, ema address, ogo, person, p ace, or event s ntended or shou d be nferred

    Th s book expresses the authors v ews and op n ons The nformat on conta ned n th s book s prov ded w thout any express, statutory, or mp ed warrant es Ne ther the authors, ORe y Med a, Inc , M crosoft Corporat on, nor ts rese ers, or d str butors w be he d ab e for any damages caused or a eged to be caused e ther d rect y or nd rect y by th s book

    Acquisitions and Developmental Editor: Russe Jones

    Production Editor: Kara Ebrah m

    Technical Reviewer: Luca Regn co

    Copyeditor: Octa Pub sh ng, Inc

    Indexer: BIM Index ng and Proofread ng Serv ces

    Cover Design: Tw st Creat ve Seatt e

    Cover Composition: E e Vo ckhausen

    Illustrator: Rebecca Demarest

  • I would like to dedicate this book to my wife, Jane, without whose steadfast love and support none of this would be possible.

    Jul an Templeman

  • Contents at a Glance

    Introduction xxi

    PART I GETTING STARTED WITH C++ .NET

    ChapTer 1 hello C++! 3

    ChapTer 2 Introducing object-oriented programming 13

    ChapTer 3 Variables and operators 23

    ChapTer 4 Using functions 37

    ChapTer 5 Decision and loop statements 57

    ChapTer 6 More about classes and objects 77

    ChapTer 7 Controlling object lifetimes 103

    ChapTer 8 Inheritance 121

    PART II MICROSOFT .NET PROGRAMMING BASICS

    ChapTer 9 Value types 143

    ChapTer 10 Operator overloading 159

    ChapTer 11 exception handling 175

    ChapTer 12 arrays and collections 197

    ChapTer 13 properties 229

    ChapTer 14 Delegates and events 245

    ChapTer 15 The .NeT Framework class library 263

    PART III USING THE .NET FRAMEWORK

    ChapTer 16 Working with files 281

    ChapTer 17 reading and writing XML 305

    ChapTer 18 Using aDO.NeT 333

    ChapTer 19 Writing a service by using Windows Communication Foundation 351

    ChapTer 20 Introducing Windows Store apps 369

    ChapTer 21 More about Windows Store apps 397

  • vi Contents at a Glance

    PART IV ADVANCED TOPICS

    ChapTer 22 Working with unmanaged code 437

    ChapTer 23 Attributes and reflection 453

    ChapTer 24 Living with COM 475

    Index 487

  • vii

    Contents

    Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

    PART I GETTING STARTED WITH C++ .NET

    Chapter 1 Hello C++! 3What s C++/CLI? 3

    Your first C++/CLI app cat on 4

    The main funct on 4

    C++ keywords and dent fiers 5

    Creat ng an executab e app cat ontheory 6

    Ed t ng the app cat on source fi es 6

    Comp ng the source fi es 6

    Runn ng and test ng the app cat on 7

    Creat ng an executab e app cat onpract ce 7

    Creat ng a project 8

    Ed t ng the C++ source code 9

    Bu d ng the executab e 9

    Execut ng the app cat on 11

    Conc us on 11

    Qu ck reference 11

    Chapter 2 Introducing object-oriented programming 13What s object-or ented programm ng? 13

    Features of object-or ented programm ng anguages 14

    Encapsu at on 14

    Inher tance 15

    Po ymorph sm 15

    C asses and objects 16

  • viii Contents

    Benefits to the deve opment fe cyc e 16

    A s mp e examp e 17

    Qu ck reference 22

    Chapter 3 Variables and operators 23What s a var ab e? 23

    The fundamenta data types 23

    Dec ar ng a var ab e 25

    Var ab e nam ng 25

    Dec ar ng mu t p e var ab es 26

    Ass gn ng va ues to var ab es 26

    Hand es and po nters 27

    Arrays 28

    Constants 28

    Typedefs 29

    The NET Framework String c ass 29

    Operators and express ons 30

    Ass gnment operators 30

    Ar thmet c operators 30

    Re at ona and og ca operators 31

    B tw se operators 32

    The ternary operator 33

    Type cast ng 33

    Operator precedence and assoc at v ty 34

    Qu ck reference 35

    Chapter 4 Using functions 37Dec ar ng funct on prototypes 38

    Dec ar ng a s mp e funct on prototype 38

    Dec ar ng parameters n a funct on prototype 39

    Dec ar ng the return type n a funct on prototype 39

    Dec ar ng defau t va ues for funct on parameters 40

  • Contents ix

    Defin ng funct on bod es 41

    Ca ng funct ons 45

    Stepp ng through the app cat on by us ng debugger 47

    Understand ng oca and g oba scope 51

    Qu ck reference 55

    Chapter 5 Decision and loop statements 57Mak ng dec s ons by us ng the if statement 57

    Perform ng one-way tests 57

    Perform ng two-way tests 61

    Perform ng mu t way tests 62

    Perform ng nested tests 64

    Mak ng dec s ons by us ng the switch Statement 65

    Defin ng s mp e switch statements 65

    Us ng fa -through n a switch statement 67

    Perform ng oops 68

    Us ng while oops 68

    Us ng for oops 70

    Us ng do-while oops 71

    Perform ng uncond t ona jumps 73

    Qu ck reference 75

    Chapter 6 More about classes and objects 77Organ z ng c asses nto header fi es and source fi es 78

    Dec ar ng a c ass n a header fi e 79

    Imp ement ng a c ass n a source fi e 81

    Creat ng objects 83

    In t a z ng objects by us ng constructors 84

    Defin ng constructors 84

    Member n t a zat on sts 86

    Defin ng c ass-w de members 87

    Defin ng c ass-w de data members 88

    Defin ng c ass-w de member funct ons 90

    C ass constructors 92

  • x Contents

    Us ng constants n c asses 93

    Us ng c ass-w de constants 93

    Us ng nstance constants 94

    Defin ng object re at onsh ps 95

    Defin ng the LoyaltyScheme C ass 95

    Imp ement ng the LoyaltyScheme c ass 96

    Creat ng and us ng LoyaltyScheme objects 97

    Test ng the app cat on 100

    Qu ck reference 101

    Chapter 7 Controlling object lifetimes 103The NET approach to object fet mes 103

    Destruct on and fina zat on 105

    Destructors 105

    F na zers 106

    Imp ement ng the destructor and fina zer for a c ass 107

    Objects and stack semant cs 110

    Copy constructors 113

    Re at ng objects w th stack semant cs 116

    Qu ck reference 119

    Chapter 8 Inheritance 121What s nher tance? 121

    Inher tance term no ogy 122

    Inher tance and code reuse 122

    Des gn ng an nher tance h erarchy 123

    A word on subst tutab ty 123

    Defin ng a base c ass 124

    Defin ng a der ved c ass 126

    Creat ng der ved c ass objects 129

    Concrete and abstract c asses 130

    Overr d ng member funct ons 131

  • Contents xi

    Protected access 136

    Defin ng sea ed c asses 137

    Abstract and sea ed 137

    Defin ng and us ng nterfaces 138

    Qu ck reference 139

    PART II MICROSOFT .NET PROGRAMMING BASICS

    Chapter 9 Value types 143Reference types and va ue types 143

    The need for va ue types 144

    Propert es of va ue types 145

    Structures 146

    Creat ng and us ng a s mp e struct 146

    Invest gat ng the structure 147

    The d fferences between structures and c asses 149

    Imp ement ng constructors for a structure 149

    Us ng one structure w th n another 150

    Copy ng structures 152

    Enumerat ons 153

    Creat ng and us ng an enumerat on 153

    Us ng enumerat ons n app cat ons 155

    Us ng memory effic ent y 156

    Qu ck reference 156

    Chapter 10 Operator overloading 159What s operator over oad ng? 159

    What types need over oaded operators? 160

    What can you over oad? 160

    Ru es of over oad ng 161

    Over oad ng operators n managed types 161

    Over oad ng ar thmet c operators 161

    Us ng stat c operator over oads 163

  • xii Contents

    What funct ons can you over oad? 166

    Imp ement ng og ca operators 167

    Imp ement ng ncrement and decrement 171

    Operators and reference types 172

    Gu de nes for prov d ng over oaded operators 173

    Qu ck reference 174

    Chapter 11 Exception handling 175What are except ons? 175

    How do except ons work? 177

    Except on types 178

    Throw ng except ons 178

    Hand ng except ons 180

    Us ng the try and catch construct 180

    Custom z ng except on hand ng 182

    Us ng the except on h erarchy 183

    Us ng except ons w th constructors 184

    Nest ng and rethrow ng except ons 185

    The finally b ock 188

    The catch() b ock 189

    Creat ng your own except on types 189

    Us ng safe cast for dynam c cast ng 191

    Us ng except ons across anguages 192

    Qu ck reference 195

    Chapter 12 Arrays and collections 197Nat ve C++ arrays 197

    Pass ng arrays to funct ons 200

    In t a z ng arrays 202

    Mu t d mens ona arrays 202

    Dynam c a ocat on and arrays 203

    Gener c types 205

    Managed arrays 207

  • Contents xiii

    The NET array c ass 212

    Bas c operat ons on arrays 213

    More advanced array operat ons 215

    Us ng enumerators 218

    Other NET co ect on c asses 219

    The List c ass 219

    The SortedList c ass 222

    Gener cs and temp ates 224

    The STL/CLR brary 224

    Qu ck reference 227

    Chapter 13 Properties 229What are propert es? 229

    The two k nds of propert es 230

    Imp ement ng sca ar propert es 231

    Errors n propert es 232

    Auto- mp emented propert es 233

    Read-on y and wr te-on y propert es 233

    Propert es, nher tance, and nterfaces 235

    Imp ement ng ndexed propert es 236

    The Bank examp e 236

    Creat ng Account c ass propert es 239

    Add ng accounts to the Bank c ass 240

    Imp ement ng the Add and Remove methods 240

    Imp ement ng an ndexed property to retr eve accounts 241

    Qu ck reference 244

    Chapter 14 Delegates and events 245What are de egates? 245

    What s the purpose of de egates? 246

    Defin ng de egates 247

    Imp ement ng de egates 247

  • xiv Contents

    What are events? 253

    Imp ement ng an event source c ass 254

    Imp ement ng an event rece ver 256

    Hook ng t a together 258

    Qu ck reference 262

    Chapter 15 The .NET Framework class library 263What s the NET Framework? 263

    The Common Language Runt me 264

    The M crosoft Intermed ate Language 264

    The Common Type System 264

    The Common Language Spec ficat on 265

    The NET Framework c ass brary 265

    Assemb es 266

    Metadata 266

    The NET Framework namespaces 268

    Us ng namespaces n C++ app cat ons 270

    The System namespace 270

    The Collections namespaces 272

    The Collections nterfaces 273

    The Diagnostics namespace 274

    The IO namespace 274

    The Windows namespaces 275

    The Net namespaces 275

    The ServiceModel namespaces 275

    The Xml namespaces 276

    The Data namespaces 276

    The Web namespaces 277

    Qu ck reference 278

  • Contents xv

    PART III USING THE .NET FRAMEWORK

    Chapter 16 Working with files 281The System::IO namespace 282

    Imp ement ng text I/O by us ng readers and wr ters 283

    Us ng TextWriter 283

    The FileStream c ass 286

    Us ng TextReader 287

    Work ng w th fi es and d rector es 290

    Gett ng nformat on about fi es and d rector es 290

    B nary I/O 298

    The BinaryWriter c ass 298

    The BinaryReader c ass 299

    Qu ck reference 303

    Chapter 17 Reading and writing XML 305XML and NET 305

    The NET XML namespaces 306

    The XML process ng c asses 306

    Pars ng XML by us ng XmlReader 307

    Pars ng XML w th va dat on 315

    Wr t ng XML by us ng XmlTextWriter 318

    Us ng XmlDocument 322

    What s the W3C DOM? 323

    The XmlDocument c ass 323

    The XmlNode c ass 325

    Qu ck reference 332

    Chapter 18 Using ADO.NET 333What s ADO NET? 334

    ADO NET data prov ders 334

    ADO NET namespaces 335

    ADO NET assemb es 336

  • xvi Contents

    Creat ng a connected app cat on 336

    Connect ng to a database 337

    Creat ng and execut ng a command 340

    Execut ng a command that mod fies data 341

    Execut ng quer es and process ng the resu ts 342

    Creat ng a d sconnected app cat on 344

    D sconnected operat on us ng a DataSet 345

    Qu ck reference 350

    Chapter 19 Writing a service by using Windows Communication Foundation 351

    What s W ndows Commun cat on Foundat on? 351

    D str buted systems 352

    Serv ces 352

    Connect v ty 353

    The ABCs of WCF 353

    Endpo nts 353

    Address 354

    B nd ng 355

    Contract 356

    Message exchange patterns 357

    Behav ors 358

    Creat ng a serv ce 359

    Wr t ng a serv ce c ent 361

    Add ng metadata to the serv ce 363

    Access ng a serv ce by us ng a proxy 365

    Qu ck reference 368

    Chapter 20 Introducing Windows Store apps 369A (br ef) h story of wr t ng W ndows user nterface app cat ons 369

    The W n32 API 369

    M crosoft Foundat on C asses 370

    W ndows Forms 370

  • Contents xvii

    W ndows Presentat on Foundat on 371

    W ndows 8 and W ndows Store 371

    Wh ch UI brary to choose? 372

    Introduc ng W ndows Store apps 372

    Ma n features of W ndows Store apps 373

    Wr t ng a W ndows Store app 374

    Creat ng your first W ndows Store app 375

    Exam n ng the project 379

    Introduc ng XAML 380

    What s XAML? 380

    XAML syntax 381

    XAML contro s 382

    Layout contro s 384

    Event hand ng 389

    C++/CX and W ndows RT 389

    W ndows RT 390

    Metadata 390

    C++/CX syntax 391

    Common namespaces 393

    Qu ck reference 395

    Chapter 21 More about Windows Store apps 397Bu d ng the bas c ca cu ator 397

    Lay ng out the number buttons 398

    Hand ng number nput 401

    Add ng ar thmet c operat ons 403

    Perform ng ca cu at ons 407

    Test ng the ca cu ator 410

    Improv ng the graph cs 412

    Hand ng d fferent number bases 416

    Us ng app bars 425

    Add ng shar ng 428

    Where next? 433

    Qu ck reference 433

  • xviii Contents

    PART IV ADVANCED TOPICS

    Chapter 22 Working with unmanaged code 437Managed vs unmanaged code 437

    M xed c asses 437

    The GCHandle type 438

    P nn ng and box ng 440

    Inter or po nters 441

    P nn ng po nters 441

    Box ng and unbox ng 442

    Box ng 443

    Unbox ng 443

    Us ng P/Invoke to ca funct ons n the W n32 API 444

    The DllImportAttribute c ass 447

    Pass ng structures 449

    Qu ck reference 452

    Chapter 23 Attributes and reflection 453Metadata and attr butes 453

    Us ng ILDASM 454

    Us ng predefined attr butes 457

    The Assemb yInfo cpp fi e 457

    Us ng the predefined attr bute c asses 458

    Defin ng your own attr butes 461

    Attr bute c ass propert es 463

    Des gn cr ter a for attr bute c asses 463

    Wr t ng a custom attr bute 463

    Us ng reflect on to obta n attr bute data 467

    The Type c ass 467

    Access ng standard attr butes 469

    Access ng custom attr bute data 470

    Qu ck reference 472

  • Contents xix

    Chapter 24 Living with COM 475COM components and the COM Interop 476

    Us ng COM components from NET code 476

    How do RCWs work? 476

    Creat ng and us ng RCWs 477

    Hand ng COM errors 480

    Late b nd ng to COM objects 481

    Us ng NET components as COM components 483

    What must NET types mp ement to be used as COM objects? 483

    Qu ck reference 485

    Index 487

  • xxi

    Introduction

    C++ s a powerfu , ndustr a -strength programm ng anguage used n tens of thou-sands of app cat ons around the wor d, and th s book w show you how to get started us ng C++ on W ndows

    Of a the anguages supported by M crosoft, C++ g ves you access to the w dest range of techno og es on the W ndows p atform, from wr t ng games, through ow- eve system software, to ne-of-bus ness app cat ons Th s book s go ng to ntroduce you to severa of the areas n wh ch C++ s used n W ndows deve opment

    For over a decade NET has become estab shed as the way to wr te desktop app -cat ons for W ndows, and t prov des a wea th of techno og es to support deve opers C++/CLI s the var ant of C++ that runs n the NET env ronment, and you can use t, a ong w th other anguages such as C#, to create r ch desktop app cat ons

    More recent y, W ndows 8 has ntroduced many new features to the W ndows oper-at ng system, but perhaps the most exc t ng s the debut of W ndows Store app cat ons These graph ca app cat ons are des gned to run on touch screen and mob e dev ces, and prov de a comp ete y new way to construct user nterfaces on W ndows C++ s one of the ma n anguages supported for W ndows Store deve opment, and th s book w g ve you an ntroduct on to these app cat ons and how to deve op them n C++/CX, another var ant of C++ ntroduced spec fica y for th s purpose

    Who should read this book

    Th s book ex sts to he p programmers earn how to wr te app cat ons us ng C++ on the W ndows p atform It w be usefu to those who want an ntroduct on to wr t ng NET app cat ons us ng C++, as we as to those who want to see how to wr te W ndows Store app cat ons

    If you are spec fica y nterested n W ndows Store app cat ons, you may w sh to ook at Build Windows 8 Apps with Microsoft Visual C++ Step by Step by Luca Regn co , Pao o P a ors , and Roberto Brunett , pub shed by M crosoft Press

  • xxii Introduction

    assumptionsTh s book expects that you have some exper ence of programm ng n a h gh- eve anguage, so that you are fam ar w th concepts such as funct ons and arrays It s qu te suffic ent to have exper ence n a procedura anguage such as V sua Bas c, and I do not assume that you have any exper ence of object-or ented programm ng n genera , or of C++ n part cu ar (a though any know edge of a cur y bracket anguage w be usefu )

    Who should not read this book

    Th s book s not su tab e for comp ete beg nners to programm ng For readers who are comp ete y new to programm ng and want to earn C++, I recommend start ng w th a book such as Programming: Principles and Practice Using C++ by Bjarne Stroustrup, pub shed by Add son-Wes ey

    Th s book s a so not su tab e for those who want to earn standard C++ or o der-sty e W n32 deve opment, because t concentrates on two M crosoft var ants (C++/CLI and C++/CX) and does not cover top cs such as the CLR or MFC n any deta

    Organization of this book

    Th s book s d v ded nto four sect ons

    Part I, Gett ng Started, ntroduces the ma n parts of the C++ anguage, gett ng you used to cod ng n C++ and bu d ng app cat ons n V sua Stud o 2012

    Part II, M crosoft NET Programm ng Bas cs, cont nues by ntroduc ng those parts of C++ that are spec fic to M crosofts C++/CLI anguage

    Part III, Us ng the NET Framework, covers the ma n features n the NET Framework brar es used for wr t ng NET app cat ons Th s part nc udes d scuss on of work ng w th fi es, XML and databases, and creat ng graph ca app cat ons

    Part IV, Advanced Top cs, covers some more advanced mater a , nc ud ng deta s for work ng w th egacy code

  • Introduction xxiii

    Finding your best starting point in this bookThe var ous sect ons of th s book cover a w de range of techno og es assoc ated w th C++ on the W ndows p atform Depend ng on your needs and your ex st ng under-stand ng of C++, you may w sh to focus on spec fic areas of the book Use the fo ow ng tab e to determ ne how best to proceed through the book

    If you are Follow these steps

    New to C++ Read Part carefu y before cont nu ng to the rest of the book.

    Fam ar w th OO programm ng but not w th C++ Read Part carefu y, but you can om t Chapter 2.

    Fam ar w th C++ Rev ew Part , ook ng for the d fferences between standard C++ and C++/CL .

    Fam ar w th .NET, but not W ndows Store app cat ons.

    Read Chapters 20 and 21.

    Most of the books chapters nc ude exerc ses that et you try out the concepts you have just earned So ut ons to these exerc ses can be down oaded us ng the compan on code nk from th s books web page on ore y com See the Code samp es sect on for deta s on how to down oad the compan on code

    Conventions and features in this book

    Th s book presents nformat on us ng convent ons des gned to make the nformat on readab e and easy to fo ow

    Each exerc se cons sts of a ser es of tasks, presented as numbered steps (1, 2, and so on) st ng each act on you must take to comp ete the exerc se

    Boxed e ements w th abe s such as Note prov de add t ona nformat on or a ternat ve methods for comp et ng a step successfu y

    Text that you type (apart from code b ocks) appears n bo d

    A p us s gn (+) between two key names means that you must press those keys at the same t me For examp e, Press A t+Tab means that you ho d down the A t key wh e you press the Tab key

    A vert ca bar between two or more menu tems (e g , F e C ose) means that you shou d se ect the first menu or menu tem, then the next, and so on

  • xxiv Introduction

    System requirements

    You w need the fo ow ng hardware and software to comp ete the pract ce exerc ses n th s book

    One of W ndows 7, W ndows 8, W ndows Server 2008 w th Serv ce Pack 2, or W ndows Server 2008 R2 Note that f you want to bu d and run the W ndows Store app cat ons featured n Chapters 20 and 21, you w need W ndows 8

    V sua Stud o 2012, any ed t on

    A computer that has a 1 6 GHz or faster processor (2 GHz s recommended)

    1 GB (32 B t) or 2 GB (64 B t) RAM

    3 5 GB of ava ab e hard d sk space

    5400 RPM hard d sk dr ve

    D rectX 9 capab e v deo card runn ng at 1024 x 768 or h gher-reso ut on d sp ay

    DVD-ROM dr ve ( f nsta ng V sua Stud o from DVD)

    Internet connect on to down oad software or chapter examp es

    Depend ng on your W ndows configurat on, you m ght requ re Loca Adm n strator r ghts to nsta or configure V sua Stud o 2012

    Code samples

    Most of the chapters n th s book nc ude exerc ses that et you nteract ve y try out new mater a earned n the ma n text A samp e projects, n both the r pre-exerc se and post-exerc se formats, can be down oaded from the fo ow ng page

    http://aka.ms/VCCLISbS/files

  • Introduction xxv

    Acknowledgments

    Produc ng a book nvo ves a number of peop e, and Id ke to thank the fo ow ng n part cu ar

    Id ke to thank a at M crosoft Press and ORe y for the r he p and support, es-pec a y Devon Musgrave at M crosoft for nv t ng me to start th s project, and Russe Jones at ORe y for prov d ng so much he p w th wr t ng and ed tor a matters, and espec a y h s gu dance n us ng the (not a ways good-tempered) Word temp ates

    The techn ca qua ty of the book has been great y mproved by Luca Regn co , who as tech rev ewer po nted out numerous errors and om ss ons I espec a y va ue h s nput on the W ndows Store chapters

    Kara Ebrah m at ORe y, a ong w th D anne Russe and Bob Russe at Octa Pub sh-ng, prov ded exce ent ed tor a support and made sure everyth ng got done on t me

    And ast y, Id ke to thank my fam y, who have put up w th a the extra work n-vo ved n wr t ng a book, and are probab y hop ng that th s s ast one for a wh e!

    Errata and book support

    Weve made every effort to ensure the accuracy of th s book and ts compan on con-tent Any errors that have been reported s nce th s book was pub shed are sted on our M crosoft Press s te at ore y com

    http://aka.ms/VCCLISbS/errata

    If you find an error that s not a ready sted, you can report t to us through the same page

    If you need add t ona support, ema M crosoft Press Book Support at [email protected]

    P ease note that product support for M crosoft software s not offered through the addresses above

  • xxvi Introduction

    We want to hear from you

    At M crosoft Press, your sat sfact on s our top pr or ty, and your feedback our most va uab e asset P ease te us what you th nk of th s book at

    http://www.microsoft.com/learning/booksurvey

    The survey s short, and we read every one of your comments and deas Thanks n advance for your nput!

    Stay in touch

    Lets keep the conversat on go ng! Were on Tw tter http://twitter.com/MicrosoftPress

  • 1

    PART I

    Getting started with C++ .NET

    CHAPTER 1 He o C++! 3

    CHAPTER 2 Introduc ng object-or ented programm ng 13

    CHAPTER 3 Var ab es and operators 23

    CHAPTER 4 Us ng funct ons 37

    CHAPTER 5 Dec s on and oop statements 57

    CHAPTER 6 More about c asses and objects 77

    CHAPTER 7 Contro ng object fet mes 103

    CHAPTER 8 Inher tance 121

  • 3

    C H A P T E R 1

    hello C++!

    after completing this chapter, you will be able to

    Recogn ze C++ funct ons

    Recogn ze C++ keywords and dent fiers

    Create a C++ app cat on

    We come to the exc t ng wor d of programm ng M crosoft NET w th M crosoft V sua C++ Th s chapter ntroduces the C++/CLI anguage and shows you how to perform s mp e nput/out-put (I/O)

    What is C++/CLI?

    C++/CLI s a vers on of the C++ programm ng anguage des gned to run on the NET Framework It has been ava ab e s nce M crosoft V sua Stud o 2005 and s the subject of an nternat ona stan-dard You can find deta s of the ECMA standard at http://www.ecma-international.org/publications/standards/Ecma-372.htm

    To ach eve th s, some changes had to be made to standard C++ There are some th ngs that you can do n standard C++ that are not perm tted n C++/CLI (for examp e, you cannot nher t from mu t p e base c asses) and there have been some changes to the anguage geared to support NET features (such as nterfaces and propert es) and to work w th the NET Runt me

    Why wou d you choose to use C++/CLI to wr te NET code nstead of another NET anguage such as C#? Apart from persona preference, there are two very good reasons to choose C++/CLI The first s for nteroperab ty; C++/CLI makes t s mp e to ncorporate standard C++ code nto NET projects The second s that we have a NET vers on of the C++ Standard Temp ate L brary (STL), and so peop e used to cod ng aga nst the STL w find t poss b e to work n the same way n NET

    Even f ne ther of these reasons app es to you, C++/CLI s st a perfect y good way to earn about NET programm ng because t exposes a of the features that you need to wr te NET programs and exp ore the NET p atform

  • 4 Microsoft Visual C++/CLI Step by Step

    Your first C++/CLI application

    Its t me to get our hands d rty w th a s mp e C++/CLI app cat on Of course, no programm ng book wou d be comp ete w thout nc ud ng the customary He o Wor d app cat on, so ets start w th that

    using namespace System; int main() { Console::WriteLine("Hello, World!"); return 0; }

    Th s short app cat on ustrates some fundamenta C++/CLI concepts

    The first ne (wh ch beg ns w th using) nforms the comp er that youre us ng the NET System brary Many d fferent brar es cou d be used n a s ng e project; the using statement spec fies

    to the comp er wh ch brary you want to use

    The rest of the app cat on s an examp e of a C++ function A b ocks of code n C++ are ca ed funct onstheres no such th ng as a procedure or a subrout ne Each C++ funct on conta ns the header (the first ne of th s app cat on) and the funct on body (a of the text between the braces, { and }) The header shows the return type of the funct on ( n th s case int, short for integer), the name of the funct on (main), and the st of parameters ns de round brackets Note that you st need to nc ude the round brackets even f you dont have any-th ng to pass to the funct on

    A statements n C++ are term nated w th a sem co on

    Of the s x nes of code n the examp e app cat on, on y two conta n C++ statements the Console ne and the return ne The Console ne outputs characters to the conso e, and the argument to the

    funct on cons sts of the str ng that you want to output The return ne ex ts from the funct on n th s case, the app cat on, because there s on y one funct onand returns zero, wh ch s the standard va ue to return when execut on s successfu

    The main functionWhy s the on y funct on n the prev ous examp e ca ed main? The s mp e answer s that the code wont comp e f t snt! However, t m ght be more usefu to exp a n how the anguage works

    A norma C++ app cat on conta ns many funct ons (and a so many c asses, as s d scussed n Chapter 2, Introduc ng object-or ented programm ng) How does the comp er know wh ch funct on shou d be ca ed first? Obv ous y, you cant a ow the comp er to just random y choose a funct on The ru e s that the comp er a ways generates code that ooks for a funct on named main If you om t the main funct on, the comp er reports an error and doesnt create a fin shed executab e app cat on

  • 6 Microsoft Visual C++/CLI Step by Step

    Outs de of these restr ct ons, any dent fier w work However, some cho ces are not recommend-ed, such as the fo ow ng

    Identifier Reason its not recommended

    ma n Cou d be confused w th the funct on ma n.

    NT Too c ose to the reserved word nt.

    B4ugotxtme Just too crypt c!

    dent fier1 Underscores at the beg nn ng of names are a owed, but they are not recommended because comp ers often use ead ng underscores when creat ng nterna var ab e names, and they are a so used for var ab es n system code. To avo d potent a nam ng confl cts, you shou d not use ead ng underscores.

    Creating an executable applicationtheory

    Severa stages are requ red to bu d an executab e app cat on; M crosoft V sua Stud o 2012 he ps you accomp sh th s by automat ng them To exam ne and understand these stages, however, ets ook at them br efly You see these stages aga n ater n the chapter when we bu d our first app cat on

    Editing the application source filesBefore you can create an app cat on, you must wr te someth ng V sua Stud o 2012 prov des an ntegrated C++ ed tor, comp ete w th co or syntax h gh ght ng and M crosoft Inte Sense to show funct on parameter nformat on and prov de word comp et on

    Compiling the source filesThe C++/CLI comp er s the too for convert ng text source fi es nto someth ng that can be executed by a computer processor The comp er takes your source fi es (wh ch usua y have a .cpp extens on) and bu ds them nto e ther a stand-a one executab e fi e (w th a .exe extens on) or a brary fi e to be used n other projects (w th a .dll extens on)

    Standard C++ and CIf you have ever worked w th standard C++ or C, you m ght be fam ar w th the dea of comp -ng to object fi es and then nk ng w th brar es to bu d the fina executab e fi ewh ch s common y referred to s mp y as an executab e A though you can comp e to the equ va ent of an object fi e (ca ed a module n the NET wor d) and then nk those together by us ng a too ca ed the assembly linker, V sua Stud o takes you stra ght from source to executab e w thout you see ng the ntermed ate step

  • CHAPTER 1 He o C++! 7

    running and testing the applicationAfter you have successfu y bu t the app cat on, you need to run t and test t

    For many deve opment env ronments, runn ng and test ng s often the most d fficu t part of the app cat on deve opment cyc e However, V sua Stud o 2012 has yet another ace up ts s eeve the ntegrated debugger The debugger has a r ch set of features w th wh ch you can eas y perform run-t me debugg ng, such as sett ng breakpoints and variable watches

    Creating an executable applicationpractice

    Go ahead and start V sua Stud o 2012 An nv t ng y b ank w ndow appears on your screen

    Th s w ndow s the powerfu V sua Stud o ntegrated deve opment env ronment (IDE) It conta ns a the too s you need to create fu -featured, easy-to-use app cat ons

    Note This book was written by using the Release Candidate (RC) version of Visual Studio 2012. As a result, screen shots and other details might differ from the version youre using when you read this.

  • 8 Microsoft Visual C++/CLI Step by Step

    Creating a projectThe first task s to create a new project for the He o, Wor d program

    1. In V sua Stud o, on the F e menu, po nt to New, and then c ck Project (A ternat ve y, you can press Ctr +Sh ft+N )

    Note I am using the Professional version of Visual Studio 2012. If you are using oth-er versions, the way in which you create a project might be different. For example, in the Express version, you will find New Project on the File menu.

    The New Project d a og box opens

    2. In the nav gat on pane on the eft, under Temp ates, c ck V sua C++, and then c ck CLR In the center pane, c ck CLR Conso e App cat on and then, toward the bottom of the d a og box, n the Name box, type HelloWorld

    Note Depending on how Visual Studio has been set up, you might find Visual C++ under the Other Languages node.

    3. C ck the Locat on st and se ect a ocat on for your new project or c ck Browse and nav gate to an appropr ate d rectory

  • CHAPTER 1 He o C++! 9

    4. C ck OK to create the project

    The w zard correct y n t a zes a the comp er sett ngs for a conso e project

    editing the C++ source codeThe w zard creates a project for you w th a the fi es needed for a s mp e conso e app cat on It a so opens the ma n source fi e n the ed tor that conta ns just the code we want

    Not ce that the keywords automat ca y appear n b ue (prov ded that you spe them correct y)

    There are a few th ngs n the automat ca y generated source code that we dont need, so ets remove them Th s w g ve you some pract ce n us ng the ed tor as we as mak ng the code eas er to understand The app cat on s not go ng to rece ve any command- ne arguments when you run t, so remove everyth ng between the open ng and c os ng parentheses fo ow ng main n th s examp e, array ^args In add t on, the L before the Hello World str ng snt necessary e ther (for reasons that I exp a n ater), so you can remove that, as we

    Building the executableThe next step s to bu d the executab e The term build n V sua Stud o 2012 refers to comp ng and nk ng the app cat on V sua Stud o comp es any source fi es that have changed s nce the ast bu d

    and f no comp e errors were generatedperforms a nk

    To bu d the executab e, on the Bu d menu, c ck Bu d So ut on or press F7

  • 10 Microsoft Visual C++/CLI Step by Step

    Note The shortcut keys might differ depending on the version of Visual Studio you are us-ing. For example, in the Ultimate edition, the shortcut is F6.

    An Output w ndow opens near the bottom of the V sua Stud o w ndow, show ng the bu d prog-ress If no errors are encountered, the message Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped w appear n the Output w ndow If th s w ndow s c osed, you can open t by se ect ng Output from the V ew menu

    If any prob ems occur, the Error L st w ndow w conta n a st of errors and warn ngs

    You can doub e-c ck the error ne n the Error L st w ndow to p ace the cursor at the ne n the source fi e where the comp er encountered the error F x the error (you m ght have m sspe ed a key-word or forgotten a sem co on) and rebu d the project If the Error L st pane s c osed, you can open t by se ect ng Error L st from the V ew menu

    how should you treat warnings?A ways treat warn ngs as errors n other words, get r d of them Warn ngs are there for a reason; theyre te ng you that your code s not correct

  • CHAPTER 1 He o C++! 11

    executing the applicationAfter youve e m nated a errors and youve successfu y bu t the project, you can fina y execute the app cat on On the Debug menu, c ck Start W thout Debugg ng to run the app cat on You can a so press Ctr +F5 to execute the app cat on

    You see the output of your app cat on, w th the message Press any key to cont nue at the bot-tom of the output Th s ne s added by the IDE so that the conso e w ndow doesnt s mp y d sappear when the app cat on has fin shed runn ng

    Conclusion

    A though the examp e n th s chapter snt the most exc t ng app cat on ever wr tten, t demonstrates some key C++ deve opment po nts It ntroduces the V sua Stud o 2012 IDE and the ab ty to comp e and nk a app cat on, and t serves as an ntroduct on to the C++/CLI anguage

    Now, theres no turn ng back Every new C++/CLI and V sua Stud o 2012 feature that you earn about w fire your mag nat on to earn more and be ncreas ng y product ve Software deve opment s an exc t ng wor d

    F na y, dont forget to have some fun Go back and try a few var at ons on the examp e app cat on, c ck a few menus, and take some t me to become fam ar w th the env ronment

    Quick reference

    To Do this

    Create a new project n V sua Stud o 2012. C ck F e New Project, or press Ctr +Sh ft+N. n the Express vers on, on the F e menu, c ck New Project.

    Add a fi e to a project. C ck F e New F e, or press Ctr +N.

    Bu d a V sua Stud o 2012 project. C ck Bu d Bu d So ut on, or press Ctr +Sh ft+B.

    Execute a program from w th n V sua Stud o 2012. C ck Debug Start W thout Debugg ng, or press Ctr +F5.

  • 13

    C H A P T E R 2

    Introducing object-oriented programming

    after completing this chapter, you will be able to

    Descr be the key concepts of object-or ented programm ng

    Understand how these concepts are supported by C++ anguage constructs

    Understand the major deve opment benefits of object-or ented programm ng

    Create and use s mp e c asses

    What is object-oriented programming?

    Object-or ented programm ng s a parad gm that prov des a natura way to deve op many k nds of systems We perce ve the wor d as cons st ng of objects tab es, cha rs, computers, cars, bank ac-counts, footba games, and so on It s a natura human tra t to try to organ ze these objects, arrang-ng them nto some form of c ass ficat on and choos ng to h gh ght certa n features of objects n pref-erence to others So, dogs and cats are mamma s, toasters and refr gerators are app ances, sw mm ng and tenn s are sports, Toyotas and Fords are cars, trucks and cars are veh c es, and so on

    There can be many eve s to these categor es and many ways to c ass fy the objects n the wor d How peop e c ass fy th ngs depends to a arge extent on what they want to do w th them as we as the re evant features of the objects themse ves For examp e, a reta er of househo d app ances s ke y to use d fferent categor esposs b y deeper and r cherfor ts products than a typ ca home-

    owner When group ng objects nto c ass ficat on schemes, we a so tend to h gh ght certa n attr butes of objects n preference to others For nstance, to an eng neer, a cars co or m ght not matter, but t m ght figure heav y n the menta mode of car c ass ficat ons used by a Ferrar sa esperson

    Object-or ented programm ng ets us bu d h erarch es of objects, creat ng them and defin ng how they are re ated As ong ago as the 1960s, researchers rea zed that many computer programs mod-e ed ent t es that can be named, and that the r propert es and behav or can be descr bed Examp es of such objects m ght be bank accounts, arrays, fi es, and users, a of wh ch are ana ogous to objects n the rea wor d

  • 14 Microsoft Visual C++/CLI Step by Step

    Object-or ented programm ng can crude y be character zed as dent fy ng the objects re evant to the prob em, organ z ng them nto h erarch es, add ng attr butes to the objects to descr be the features re evant to the prob em context, and add ng funct ons (methods) to the objects such that they can perform the r requ red tasks The deta s are a tt e more comp cated, but essent a y, t s a s mp e process

    Yet, s mp e doesnt necessar y mean easy A co ect on of objects cou d potent a y be c ass fied n many ways The ab ty to dent fy the mportant attr butes of objects and to form good abstract ons and appropr ate h erarch es s cruc a Even w th n the context of a prob em doma n, ts somet mes hard to determ ne the correct eve s of abstract on and su tab e c ass ficat on h erarch es Just dec d ng wh ch c ass or group ng an object be ongs to can be very d fficu t As ph osopher Ludw g W ttgen-ste n po nted out n h s 1953 book Philosophical Investigations, some objects w bear more of a fam y resemb ance to a concept than others; for examp e, hockey and tenn s are more obv ous y sports than are chess and synchron zed sw mm ng

    Features of object-oriented programming languages

    Ive a ready po nted out that object-or ented programm ng means defin ng and bu d ng h erarch es of objects and defin ng the r propert es and behav or You can do th s to a certa n extent n any programm ng anguage, just the same as you cou d, theoret ca y, take a tr p over the Rock es n a go f cart, but t s much eas er to do object-or ented programm ng f you use a anguage that s des gned to support object-or ented programm ng methods

    Object-or ented programm ng anguages such as C++ and C# are character zed by three key features encapsulation, inheritance, and polymorphism These features support th s natura process of dent fy ng and c ass fy ng objects Lets take a c oser ook at each one

    encapsulationOne of the prob ems faced by software deve opers s that the systems we are deve op ng are becom-ng ncreas ng y arger and more comp ex Encapsu at on he ps to keep th ngs manageab e by break-ng an app cat on down nto sma , se f-conta ned ent t es For examp e, f youre bu d ng an account-ng system, you probab y need objects to represent accounts and nvo ces After youve deve oped the Account c ass, you no onger need to worry about the deta s of the mp ementat on of the c ass You can use the c ass anywhere n your app cat on n much the same way you wou d use a bu t- n type, such as an nteger The c ass exposes the essent a features of the Account object wh e h d ng the mp ementat on deta s

    The accounts name and the state of ts ba ance are some of the attr butes of the object n wh ch the c ent s nterested and needs to know Deta s of how the account name s storedwhether ts an array of 50 characters or a str ng object, or the fact that the accounts ba ance s ma nta ned as a currency var ab eare rre evant to the c ent The process of h d ng the data structures and mp e-mentat on deta s of an object from other objects n the system s ca ed encapsulation (somet mes a so known as data hiding), and t prevents the other objects from access ng deta s about wh ch they

  • CHAPTER 2 ntroduc ng object or ented programm ng 15

    dont need to know Encapsu at on makes arge programs eas er to comprehend; data h d ng makes them more robust

    Objects can nteract w th other objects through on y the r pub c y exposed attr butes and methods The more attr butes and methods that are pub c y exposed, the more d fficu t t w be to mod fy the c ass w thout affect ng the code that uses the c ass When done proper y, the nner work ngs of a c ass can be changed w thout affect ng the code that uses objects created, or instantiated, from that c ass The programmer wou d have to worry on y about the methods n the c ass that accessed that var ab e rather than worry about a the p aces n the app cat on that an object nstant ated from that c ass m ght be ca ed

    InheritanceThe natura tendency for humans to c ass fy objects nto h erarch es s usefu from a programmers perspect ve and s supported n object-or ented anguages, nc ud ng C++, by nher tance Inher -tance prov des two benefits to the C++ programmer F rst, and most mportant, t ets you bu d h erarch es that express the is a re at onsh ps between types Suppose that you have two c asses, SavingsAccount and CheckingAccount, both of wh ch are der ved from the parent Account c ass If you have a funct on that requ res an Account as an argument, you can pass t a SavingsAccount or a CheckingAccount because both c asses are types of Account Account s a genera c ass ficat on, and CheckingAccount and SavingsAccount are more spec fic types The second benefit of object-or ented programm ng s that c asses can nher t features from c asses h gher n the h erarchy Instead of deve -op ng new c asses from scratch, new c asses can nher t the funct ona ty of ex st ng c asses and then mod fy or extend th s funct ona ty The parent c ass from wh ch the new c ass nher ts s known as the base class, and the new c ass s known as the derived class

    One of the major tasks fac ng deve opers s find ng appropr ate c ass ficat ons for the objects and c asses n the r programs For examp e, f you need to deve op c asses for a dr v ng game, t makes more sense for you to deve op a genera car c ass and then use th s c ass as a base c ass for spec fic car types such as sportscar or truck These der ved c asses wou d then extend or mod fy the genera car c ass by add ng new attr butes and methods or by overr d ng ex st ng methods Compos ng objects from subobjectsfor examp e, a car cons st ng of an eng ne and a chass scan a so s mp fy the de-ve opment effort Do ng t th s way, each of the objects s s mp er and therefore eas er to des gn and mp ement than the co ect ve who e

    polymorphismThe th rd feature of object-or ented programm ng anguages s polymorphism, wh ch s Greek for many forms It s qu te a hard concept to define, so I use some examp es to show you what po y-morph sm s and eave the prec se defin t ons to more academ c wr ters

    Po ymorph sm essent a y means that c asses can have the same behav or but mp ement t n d fferent ways Cons der severa d fferent types of veh c e they a need to be started, so n program-m ng terms, we cou d say that a veh c es have start funct ona ty Exact y how start ng s mp e-mented depends on the veh c e If t s a Ford Mode T, start ng w mean manua y crank ng the

  • 16 Microsoft Visual C++/CLI Step by Step

    start ng hand e at the front of the veh c e, but f t s a modern car, start ng w mean turn ng the key n the gn t on If the veh c e s a steam ocomot ve, start ng w be a very d fferent and more comp ex process, ndeed

    As another examp e, cons der the aforement oned SavingsAccount and CheckingAccount types A types der ved from Account share certa n funct ona ty, such as the ab ty to depos t, w thdraw, and query the ba ance They m ght mp ement them n d fferent ways because CheckingAccount m ght perm t an overdraft, whereas SavingsAccount m ght accrue nterest, but they a work the same way Th s means that f Im passed an Account, t doesnt matter exact y what type of account t s; I can st depos t funds, w thdraw funds, and query the ba ance Th s funct ona ty s usefu n programm ng terms because t g ves you the ab ty to work w th gener c object typesaccounts and veh c eswhen youre not concerned w th the way n wh ch each c ass mp ements funct ona ty

    Classes and objects

    Up to th s po nt n the chapter, the terms c ass and object have been used fa r y nterchangeab y However, c asses and objects arent the same th ng, and we need to c ar fy the d fferences between these terms As the name mp es, object-or ented programm ng s about objects An object s com-posed of data that descr bes the object and the operat ons that can be performed on the object However, when you create an app cat on n C++, you define c asses, not objects

    A class s a user-defined type; t encapsu ates both the data and the methods that work on that data W th the except on of stat c funct ons, you cannot use c asses d rect y A c ass s ke a temp ate, wh ch s used to create ( nstant ate) objects Just as you have to dec are an int var ab e before you can use t, you a so have to nstant ate an object of the c ass before you can use t

    For examp e, you wou d not define an Animal object Instead, you wou d define an Animal c ass a ong w th ts attr butes and methods The c ass represents the concept, so the Animal c ass does not represent a spec fic an ma but the c ass of a an ma s When you want to use an Animal object, you have to nstant ate an Animal object from the c ass The c ass can be cons dered as the ab-stract representat on of an ent ty, whereas the nstant at on of the c assthe object s the concrete representat on

    Benefits to the development life cycle

    There are three key benefits to object-or ented programm ng comprehensibility, reusability, and extensibility Break ng code down nto c asses makes t more comprehens b e by mpos ng a structure as programs grow arger and arger The dea s to assemb e object-or ented systems from prewr tten c asses and to make the requ red mod ficat ons to support the new requ rements by us ng nher tance

  • CHAPTER 2 ntroduc ng object or ented programm ng 17

    and compos t on to der ve new c asses from the ex st ng c asses The ex st ng c asses are reused as bu d ng b ocks and not a tered n any way Creat ng systems from reusab e components natura y eads to h gher product v ty, wh ch s probab y the most frequent y c ted benefit of object-or ented approaches Object-or ented programm ng shou d a so resu t n h gher-qua ty systems When you reuse c asses, t means that you are us ng code that has a ready been tested and proven n ear er projects; thus, t s ke y to conta n fewer bugs than c asses deve oped from scratch Over t me, any bugs that m ght have ex sted have been found and fixed n these c asses, whereas code that s wr tten from scratch has yet to pass through the same bug detect on and fix ng process

    The features (encapsu at on, nher tance, and po ymorph sm) of object-or ented programm ng a so prov de benefits Encapsu at on makes t eas er to sca e up from sma systems to arge systems For the most part, regard ess of the s ze of the system, the deve oper s s mp y creat ng objects Large sys-tems m ght requ re more objects than sma systems, but the eve of comp ex ty fac ng the deve oper s not s gn ficant y ncreased Inher tance he ps to mprove the flex b ty and extens b ty of systems, hence reduc ng the r costs to ma nta n Der v ng new c asses from ex st ng c asses prov des add t ona funct ona ty and makes t poss b e to extend the software w thout a ter ng the ex st ng c asses

    F na y, data h d ng a so eads to more secure systems The state of an object can be mod fied on y by ts pub c y exposed methods, wh ch ncreases the pred ctab ty of object behav or

    A simple example

    The fo ow ng s mp e examp e shou d serve to show you how to create a c ass, nstant ate objects, and access member funct ons and attr butes

    1. Start M crosoft V sua Stud o 2012

    2. On the F e menu, po nt to New, and then c ck Project

    The New Project d a og box opens

    3. In the nav gat on pane on the eft, under Temp ates, c ck V sua C++, and then c ck CLR

    4. In the center pane choose CLR Conso e App cat on

    5. Toward the bottom of the d a og box, n the Name box, type Animals

    6. C ck the Locat on box and se ect a ocat on for the new project (or c ck Browse to find t), and then c ck OK

  • 18 Microsoft Visual C++/CLI Step by Step

    7. The fi e An ma s cpp shou d a ready be open n the ed tor If t s not, n So ut on Exp orer, n the Source F es fo der, doub e-c ck the An ma s cpp fi e

    8. Immed ate y under the using namespace System; ne, add the fo ow ng c ass defin t on

    ref class Animal { int legs; String ^name; };

    To dec are a c ass n C++, you use the keywords ref class fo owed by a name for the c assAnimal n th s examp eand then you st a the member var ab es and funct ons for the c ass between open ng and c os ng braces ({ and })

    So far, you have created an Animal c ass w th an int var ab e for the number of ts egs and a String var ab e for ts name As t stands, no other app cat on or c ass w be ab e to access these var ab es The members of a c assdata and methodsare pr vate by defau t and can on y be accessed by methods of the c ass tse f C++ prov des three access mod fiers, public, private, and protected, wh ch you use to spec fy the v s b ty of the var ous members of the c ass

    9. Add the keyword public fo owed by a co on ( ) on a new ne between the open ng brace and the first var ab e dec arat on

  • CHAPTER 2 ntroduc ng object or ented programm ng 19

    ref class Animal { public: int legs: String ^name; };

    By dec ar ng the var ab es after the keyword public, you make both of them access b e How-ever, t s not usua y a good dea to a ow other c asses and parts of your app cat on access to the var ab es of a c ass

    As d scussed ear er n the sect on on encapsu at on, ts better to keep the mp ementat on deta s of a c ass h dden from users of that c ass and to contro the access to the c asss data through funct ons In the next step, we use the keyword private to prevent d rect access to the String var ab e of the c ass We eave the int var ab e legs w th pub c access, s mp y to show how t can then be d rect y accessed by the ma n app cat on

    10. Add the keyword private fo owed by a co on ( ) between the first int var ab e and the second String var ab e

    ref class Animal { public: int legs; private: String ^name; };

    To prov de access to the pr vate String var ab e, pub c accessor funct ons and methods need to be added to the c ass to a ow other funct ons to man pu ate ts va ue

    11. After the dec arat on of the int var ab e and before the private access mod fier, add the fo ow-ng method dec arat ons or mp ementat on nes

    void SetName(String ^nm) { name = nm; } String^ GetName() { return name; }

    Because these methods are sma funct ons, ts eas est to dec are and mp ement them as inline functions In ne funct ons are exp a ned further n Chapter 6, More about c asses and objects, when we go nto c asses n greater deta

  • 20 Microsoft Visual C++/CLI Step by Step

    You have probab y not ced the ref keyword Th s C++/CLI keyword s mp fies the nteract on w th NET Framework components By p ac ng ref n front of the class keyword, the c ass becomes a man-aged c ass When the object s nstant ated, t s created on the Common Language Runt me (CLR) heap The fet me of an object nstant ated from the c ass s managed by the NET Frameworks gar-bage co ector When the object goes out of scope, the memory used by the object s garbage-co -ected automat ca y ref c asses are known as reference types because the var ab e does not actua y conta n the object; rather t s a po nter to the memory ocat on of the object, known as a handle

    However, there are performance ssues to cons der when us ng reference types The memory has to be a ocated from the managed heap, wh ch cou d force a garbage co ect on to occur In add t on, reference types must be accessed v a the r hand es, affect ng both the s ze and speed of the comp ed app cat on

    Because of these performance ssues, the NET Framework a so supports value types Va ue types are objects created on the stack The var ab e conta ns the object tse f rather than a hand e to the object Hence, the var ab e doesnt have to be dereferenced to man pu ate the object, wh ch of course mproves performance To dec are a va ue type c ass, the value keyword shou d be used nstead of the ref keyword In th s case, the var ab es wou d have been created on the stack Instead of dec ar ng hand es for th s c ass and then creat ng the objects on the CLR heap, the objects are dec ared n the same way as the bu t- n C++ types, and the member var ab es are accessed by the dot operator

    Now that you have wr tten the Animal c ass, your app cat on can use t just as the app cat on wou d use a bu t- n type

    1. In the main funct on, de ete the fo ow ng ne

    Console::WriteLine(L"Hello World");

    2. Dec are and create two Animal objects n your main funct on

    Animal cat, dog;

    3. Use the member funct on SetName to ass gn the names Cat and Dog to the respect ve cat and dog objects, and set the legs var ab e for both objects to 4

    cat.SetName("Cat"); cat.legs = 4; dog.SetName("Dog"); dog.legs = 4;

    To access the member var ab es and funct ons of an object, you use the dot operator ( ) You can read th s as set the name of the cat to Cat, w th the dot operator re at ng the funct on to the object on wh ch t s operat ng

    Hav ng created a coup e of Animal objects and ass gned data to them, you are now go ng to d sp ay that data on the screen

  • CHAPTER 2 ntroduc ng object or ented programm ng 21

    4. Add the fo ow ng nes

    Console::WriteLine("Animal 1"); Console::Write("Name: "); Console::WriteLine(cat.GetName()); Console::Write("Legs: "); Console::WriteLine(cat.legs); Console::WriteLine(); Console::WriteLine("Animal 2"); Console::Write("Name: "); Console::WriteLine(dog.GetName()); Console::Write("Legs: "); Console::WriteLine(dog.legs); Console::WriteLine();

    Now, ts t me to bu d the app cat on

    5. On the Bu d menu, c ck Bu d So ut on or use the keyboard shortcut F6

    In case youve had any prob ems putt ng the app cat on together from the fragments n the preced ng steps, the ent re app cat on s sted here

    #include "stdafx.h" using namespace System; ref class Animal { public: int legs; void SetName(String ^nm) { name = nm; } String^ GetName() { return name; } private: String ^name; }; int main(array ^args) { Animal cat, dog; cat.SetName("Cat"); cat.legs = 4; dog.SetName("Dog"); dog.legs = 4; Console::WriteLine("Animal 1"); Console::Write("Name: "); Console::WriteLine(cat.GetName()); Console::Write("Legs: "); Console::WriteLine(cat.legs); Console::WriteLine(); Console::WriteLine("Animal 2"); Console::Write("Name: "); Console::WriteLine(dog.GetName());

  • 22 Microsoft Visual C++/CLI Step by Step

    Console::Write("Legs: "); Console::WriteLine(dog.legs); Console::WriteLine(); return 0; }

    6. If the bu d was successfu , run the app cat on by c ck ng Start W thout Debugg ng on the Debug menu, or use the keyboard shortcut Ctr +F5

    Quick reference

    To Do this

    Create a c ass. Use the keyword class.

    Contro the v s b ty of var ab es and methods. Use the access contro keywords public, private, or protected, fo owed by a co on (:).

    Dec are a reference type c ass. P ace the ref keyword before the class spec fier.

    Dec are a va ue type c ass. P ace the value keyword before the class spec fier.

    nstant ate a reference type c ass object. Use the name of the c ass when dec ar ng an object; for examp e:

    Animal cat;

  • 23

    C H A P T E R 3

    Variables and operators

    after completing this chapter, you will be able to:

    Dec are (create) var ab es

    Use the bu t- n C++ data types

    Use the M crosoft NET Framework Str ng c ass

    Ass gn va ues to a var ab e

    Create express ons by us ng the C++ operators

    Cast (change) the type of a var ab e

    In Chapter 2 Introduc ng object-or ented programm ng, you ooked at the advantages of object-or ented programm ng and deve oped a s mp e app cat on to ustrate the creat on and use of c asses

    In th s chapter, you take a c oser ook at how to create and use var ab es, the fundamenta data types of C++, how to access and use c asses from the NET Framework, and how to create express ons by us ng C++ operators

    What is a variable?

    Var ab es are ocat ons n memory where data can be temporar y stored for use by the app cat on They have a name, a type, and a va ue The va ue of the var ab e can be changed dur ng the execut on of the app cat on; hence, the name var ab e Before you can use a var ab e, you must dec are t you must spec fy ts type, and you must g ve t a name The type of a var ab e defines the a owab e range of va ues that the var ab e can ho d and the operat ons that you can perform on t

    The fundamental data types

    C++ has a bu t- n set of data types, as out ned n the fo ow ng tab e

  • CHAPTER 3 Var ab es and operators 25

    Declaring a variable

    As I ment oned ear er, you must dec are var ab es before you can use them A s mp e dec arat on cons sts of a type, fo owed by one or more var ab e names separated by commas and term nated by a sem co on, as shown n the fo ow ng examp e

    int primeNumber; double x, y, z;

    You can g ve each var ab e a qua fier before the type (for examp e, unsigned) You can a so p ace an n t a zer after the var ab e name to g ve t an n t a va ue (for examp e, int i = 0) The qua fier and the n t a zer are opt ona and are not requ red to appear n the dec arat on, but the base type and var ab e name must be present The dec arat on s term nated by a sem co on

    [qualifier] type name [initializer]; unsigned int i; // An unsigned integer variable i, note the // qualifier limiting the variable to // positive numbers. long salary = 0; // A long variable initialized to zero. double y; // A double variable without qualifier or // initializer.

    When you dec are a var ab e, the comp er does the fo ow ng

    A ocates enough memory to store the var ab e of that type and to assoc ate the name of the var ab e w th that memory ocat on

    Reserves the name of the var ab e to prevent t from be ng used by other var ab es w th n the same scope

    Note Scope refers to that part of the code for which a variable is visiblein other words, where it can be used. The concept of scope is explained more in Chapter 4, Using functions.

    Ensures that the var ab e s used n a way cons stent w th ts type For examp e, f you have dec ared a var ab e as a char, you cant store the va ue 3 7 n t

    Variable namingA C++ var ab e name can be any comb nat on of etters, numbers, and underscores, as ong as the first character of the var ab e name s a etter or an underscore A though C++ does not p ace any re-str ct ons on your cho ce of var ab e names, they shou d be mean ngfu , and you shou d be cons stent n your nam ng convent ons to ncrease the readab ty of your code C++ s case-sens t ve Th s means that myvariable and myVariable are two separate var ab es However, ts not a good dea to d fferen-t ate var ab es so e y on the bas s of case; do ng so cou d ead to confus on It wou d be easy to type a etter n the wrong case and end up us ng a comp ete y wrong var ab e!

  • 26 Microsoft Visual C++/CLI Step by Step

    Note As is mentioned in Chapter 1, Hello C++!, its not a good idea to create identifiers that begin with two underscores or an underscore followed by a capital letter (for example, A). Microsoft uses this naming convention to specify macros and Microsoft-specific key-

    words, so starting your variables with these combinations could lead to name conflicts.

    Declaring multiple variables

    You can dec are severa var ab es of the same type n the same statement s mp y by separat ng them w th commas, as demonstrated n the fo ow ng

    int x = 10, y, z = 11;

    Th s statement creates three ntegers ca ed x, y, and z The first nteger s n t a zed to 10 and the th rd to 11, whereas the second s not n t a zed

    Assigning values to variables

    You ass gn a va ue to a var ab e by us ng the ass gnment operator = (the equa s gn) The va ue on the r ght s de of the operator s stored n the var ab e, wh ch s on the eft s de When ass gn ng a va ue to a var ab e, the va ue must be ong to the same type as the var ab e, t must be a type for wh ch C++ w perform an ass gnment convers on (such as between float and ntegra types), or t must be exp c-t y converted (cast) to the correct type

    assignment conversionsAss gnment convers ons occur when var ab es on oppos te s des of an equa s gn are of d f-ferent types and the comp er can convert between the two types w thout any poss b e oss of data For nstance, ass gn ng an int to a double resu ts n an ass gnment convers on because conceptua y a the comp er has to do s to add 0 to the nteger to make the convers on

    You m ght occas ona y need to force the comp er to perform a convers on that t other-w se wou dnt do For examp e, d v d ng two ntegers resu ts n an nteger resu t f you want a float ng-po nt resu t, you can nstruct the comp er to convert one of the va ues to a doub e, as

    ustrated here

    double result = double(640) / 480;

    You g ve the name of the type to wh ch to convert, fo owed by the va ue n parentheses Th s process s ca ed casting, and t can be rather dangerous because youre d rect ng the comp er to app y a convers on that t otherw se wou d not do, and youd better be sure youre correct

  • CHAPTER 3 Var ab es and operators 27

    int x; float y; double z; x = 1; z = x; y = 3.56; x = y; // Assignment conversion from float to int // results in loss of data. // The integer 3 is stored in the variable x.

    In th s fina case the comp er w generate the warn ng C4244 = convers on from float to nt poss b e oss of data The reason for th s s because the ass gnment to an nteger w ose the fract ona part, so 3 56 w be truncated to 3

    Handles and pointers

    In standard C++, a po nter s a var ab e that ho ds the memory address of another var ab e or func-t on, wh ch means that you can use a po nter to refer nd rect y to a var ab e

    In C++/CLI, however, the runt me s manag ng memory on your beha f, and t reserves the r ght to move th ngs around to max m ze the ava ab e free memory Th s means that an object m ght not stay at the same address throughout ts fet me; thus, the address stored n your po nter m ght become out of date, ead ng to prob ems f you try to use t

    For th s reason po nters, n the trad t ona C++ sense, are not used n C++/CLI Instead, you use handles (a so known as tracking handles), wh ch a so conta n the address of a var ab e but wh ch w be updated by the runt me f t has to move the var ab e around

    A though a hand e conta ns an address and therefore can store a memory address of any data type, hand e var ab es are dec ared to be data-type spec fic A hand e to a Person object cant store the address of an Account A hand e var ab e s dec ared n the same way as the data-type var ab e, but the hand e operator ^ (caret character) s prepended to the var ab e name

    Person ^pp; // handle to a Person Account ^ac; // handle to an Account

    Note It is in fact possible to use pointers in some circumstances in C++/CLI, but that is be-yond the scope for this introductory discussion.

    You typ ca y create an object dynam ca y and obta n a hand e to t by us ng the gcnew operator, as ustrated here

    Person ^pp = gcnew Person("Fred");

  • 28 Microsoft Visual C++/CLI Step by Step

    Th s code nstructs the runt me to create a new Person object, pass ng n the str ng Fred as n t a -zat on data, and return a hand e to the object t has created

    When you access a member of an object through a hand e, you use the po nter operator (->), wh ch s d scussed n more deta n the fo ow ng chapters

    Arrays

    An array s a co ect on of data-storage ocat ons, each of wh ch ho ds the same type of data, such as a ntegers or a doub es Arrays are very usefu when you want to represent a co ect on of va ues (such as the number of days n each month or the names of company emp oyees) and you know how many you need to store

    Un ke c ass c C++, arrays n C++/CLI are objects that know how much data they are manag ng Th s makes them safer than trad t ona C++ arrays because any attempt to read or wr te past the end of the array resu ts n a run-t me error, but does not corrupt memory

    Each storage ocat on s ca ed an element of the array E ements of the array are accessed by an ndex, wh ch starts at zero and cont nues up to one ess than the array bound Why not start the ndex from one? Th s s to preserve compat b ty w th other C-type anguages, wh ch a start array ndex ng from zero

    To dec are an array, you need to spec fy the type of tem that you are go ng to store You create array objects dynam ca y by us ng the gcnew operator

    array ^arr = gcnew array(10); // Declare an array of ten integers. int x; arr[0] = 23; // The first element in the array starts at offset 0 arr[9] = 21; // The last element in the array starts at offset 9 x = arr[0]; // Use an element from the array

    Constants

    L ke var ab es, constants are named data-storage ocat ons However, un ke a var ab e, the va ue of a constant cant be changed after t has been dec ared It has to be n t a zed when ts created and cant be ass gned a new va ue ater C++ has two types of constants literal and symbolic

    A tera constant s s mp y a va ue typed nto the app cat on The statements n the fo ow ng code ass gn the tera s 40 and Dog to the respect ve var ab es noOfEmployees and name

    noOfEmployees = 40; name = "Dog";

    A symbo c constant s a constant that s represented by a name You define t n exact y the same way as a var ab e, but the qua fier must start w th the keyword const and the var ab e must be

  • CHAPTER 3 Var ab es and operators 29

    n t a zed After dec arat on, you can use the constant name anywhere that you can use a var ab e of that type, as shown n the fo ow ng

    const unsigned long noOfFullTimeEmployees = 49; const unsigned long noOfPartTimeEmployees = 234; unsigned long noOfEmployees; noOfEmployees = noOfFullTimeEmployees + noOfPartTimeEmployees;

    There are a coup e of advantages to us ng symbo c constants rather than tera constants

    The symbo c names make the app cat on more readab e The symbo c constant noOfFull TimeEmployees s more mean ngfu than the tera constant 49

    Its eas er to change a s ng e symbo c constant dec arat on than to find and rep ace a occur-rences of a tera n a app cat on

    However, us ng symbo c constants nstead of tera s can be taken too far It s not necessary to re-p ace a tera s w th constants There are some constants that are ntu t ve y obv ous to everyone and that are not go ng to change; for examp e, the number of days n a week or months n a year These va ues can be eft as tera s w thout reduc ng the readab ty or ma nta nab ty of the code

    Typedefs

    A typedef s a user-defined synonym for an ex st ng type To create a synonym for a type, you use the keyword typedef fo owed by the name of the type and the new name you are defin ng Because typedef s a C++ statement, you a so need a c os ng sem co on

    typedef unsigned int positiveNumber;

    Th s typedef dec ares positiveNumber to be a synonym of unsigned int and can be used n a dec a-rat on nstead of the actua type name

    positiveNumber one, two;

    The .NET Framework String class

    The String c ass s not a bu t- n data type ke int or long; t s a part of the NET Framework Because String snt a bu t- n type, you must nc ude some fi es n your project before the comp er w et you use t Code that wants to use the String c ass needs to nc ude the fo ow ng ne at the top of ts source code fi e

    using namespace System;

    Th s ne makes t eas er to use certa n NET c asses Because String s n the System namespace, ts fu name s System::String, but a using namespace statement such as th s makes t poss b e for you to use the name w thout qua ficat on Th s w be exp a ned n more deta ater on

  • 30 Microsoft Visual C++/CLI Step by Step

    The String c ass conta ns a arge number of methods to s mp fy man pu at ng str ngs, such as Insert and Replace

    Note After you initialize a String object, it is immutable: It cant be changed after it is cre-ated. The member functions of the String class that appear to alter strings, such as Insert and Replace, actually return a new String object, which contains the modified string. If you need to make repeated changes to a string, you should use the StringBuilder class, adding a using namespace statement for the System::Text namespace to simplify access.

    Operators and expressions

    Express ons are bu t by us ng operators that work w th datathe operandsto g ve a resu t Look at th s examp e

    remuneration = salary + bonus;

    Here the add t on operator + (p us s gn) s used to add the operands salary and bonus, and the as-s gnment operator = (equa s gn) s used to store the tota n the remuneration var ab e

    assignment operatorsYou use an ass gnment express on to ass gn a va ue to a var ab e A express ons return a va ue when eva uated, and the va ue of the ass gnment express on becomes the new va ue of the object on the eft s de Th s funct ona ty makes t poss b e to ass gn the same va ue to a group of var ab es

    noOfMammals = noOfDogs = noOfCats = 0;

    In th s examp e, a three var ab esnoOfMammals, noOfDogs, and noOfCatsare set to 0

    arithmetic operatorsC++ has 12 ar thmet c operators, 5 of wh ch operate ke the standard mathemat ca operators the add t on operator + (the p us s gn), the subtract on operator (the m nus s gn), the mu t p cat on operator * (the aster sk), the d v s on operator / (the s ash), and the modu us operator % (the percent s gn), wh ch returns the rema nder after d v s on

    result = 4 + 2 - 3; // result = 3 result = 4 * 5; // result = 20 remainder = 7 % 3; // remainder = 1

    In add t on, there are a number of ar thmet c ass gnment operators, each of wh ch cons sts of the operator and the = (equa s gn) so the add t on ass gnment operator += s a p us s gn w th an equa

  • CHAPTER 3 Var ab es and operators 31

    s gn, and we a so have =, *=, /=, %= These operators are shorthand forms that comb ne the cor-respond ng mathemat ca operat on w th the ass gnment operat on So, the fo ow ng two statements are dent ca

    a = a + 5; a += 5;

    The add t on ass gnment operator s a shortcut operators; thus, there s no d fference between the two statements In both statements, an add t on s performed, fo owed by an ass gnment The second form s just a shorter way of express ng a frequent y used operat on

    The ncrement and decrement operators are s m ar shorthand operators, but these operators on y add or subtract 1 from the va ue of the var ab e

    a++; // Adds 1 to the value of the variable a a--; // Subtracts 1 from the value of the variable a

    There are two forms of the ncrement and decrement operators the prefix form ++a or a, and the postfix forms a++ or a A though both forms add or subtract 1, n the prefix form, the math-emat ca operat on s performed before the var ab e s used n the express on; n the postfix form, the var ab e s ncremented or decremented after the var ab e has been used n the express on

    int a, b, c; a = b = c = 0; b = ++a; // a = 1, b = 1 c = a++; // c = 1, a = 2

    In th s code fragment, the fina va ues of the var ab es are a = 2, b = 1, and c = 1 The prefix ncre-ment operator express on added 1 to the va ue of a before ass gn ng the va ue of the var ab e a to the var ab e b The postfix ncrement operator express on ass gned the va ue of the var ab e a to the var ab e c and then ncremented the va ue of the var ab e a by 1

    relational and logical operatorsRe at ona operators are used to compare two va ues or express ons, return ng a va ue of true or fa se C++ has s x re at ona operators, as shown n the fo ow ng code

    a > b // returns true if a is greater than b. a >= b // returns true if a is greater than or equal to b. a < b // returns true if a is less than b. a

  • 32 Microsoft Visual C++/CLI Step by Step

    a && b // returns true if both a and b are true (a > b) && (a < c) // returns true if a is greater than b and a // is less than c a || b // returns true if either a or b are true (a > b) || (a < c) // returns true if either a is greater than b // or a is less than c

    The eva uat on of a re at ona express on stops as soon as the og ca va ue of the who e express on s determ ned, a feature known as short-circuit evaluation For examp e, the express on expr1 && expr2 s true on y f both expr1 and expr2 are true If expr1 s fa se, the fina va ue of the express on must be fa se, and therefore, expr2 s not eva uated

    The NOT operator returns the negat on of the Boo ean va ue of ts operand

    !a // returns false if a is true // returns true if a is false

    These operators are most often used n dec s on or oop structures, wh ch are d scussed n Chapter 5, Dec s on and oop statements

    Bitwise operatorsC++/CLI has s x b tw se operators the AND operator & (an ampersand), the OR operator (a vert -ca bar), the exc us ve OR operator ^ (a caret), the comp ement operator ~ (a t de), the r ght-sh ft operator >> (two r ght ang e brackets), and the eft-sh ft operator

  • CHAPTER 3 Var ab es and operators 33

    a = 5; a = a >> 2; // The bits of a will be shifted two bits to the // right and the value of 1 assigned to a.

    The ternary operatorThe ternary operator ?: (a quest on mark and a co on) acts ke an n ne if statement (See Chapter 5 for more nformat on on if statements ) The express on to the eft of the quest on mark s eva uated; f t s true, the va ue or express on between the quest on mark and the co on w be returned If t s fa se, the va ue or express on after the co on w be returned

    int a; bool b; b = true; a = b ? 1 : 2; // b is true, so a is assigned 1. b = false; a = b ? 1 : 2; // b is false, so a is assigned 2.

    Type castingC++/CLI supports the C-sty e cast operator, whereby the type to wh ch you want to convert the ex-press on s p aced n parentheses n front of the express on; for examp e, (float) 7 It a so supports five C++ cast operators

    static cast

    const cast

    dynamic cast

    safe cast

    reinterpret cast

    The static cast operator changes the data type of the var ab e, w th the type to wh ch you want to cast be ng p aced n the ang e brackets For examp e, f an express on needs to convert an int to a double, the number shou d be cast by us ng the static cast operator Heres an examp e

    int a = 10;

    double b;

    b = (int) a; // old C-style cast

    b = static_cast(a); // C++ static cast

    You use the dynamic cast operator to cast objects down or across the nher tance h erarchy The const cast operator works w th po nters, and references can be used to add or remove the const qua ficat on of the var ab e The safe cast operator s an extens on added to C++/CLI; t performs

  • CHAPTER 3 Var ab es and operators 35

    Quick reference

    To Do this

    Dec are a var ab e. Spec fy the type, fo owed by spaces and then the var ab e name, fo owed by a sem co on. For examp e:

    int number1; long longNumber1;

    Ass gn va ues to a var ab e. Use the ass gnment operator =.

    Group homogenous data together. Use an array.

    Prevent data from be ng changed. Make the var ab e a constant. For examp e:

    const int x = 10;

    Restr ct the va ues a var ab e can accept to a sma set. Dec are an enumerated constant, and dec are the var ab e to be of that type.

    Access a String c ass. Use the .NET String c ass.

    Convert one data type to another. Use the static cast operator.

    Overr de defau t operator precedence, or make the code more readab e.

    Use parentheses to group operators.

  • 37

    C H A P T E R 4

    Using functions

    after completing this chapter, you will be able to:

    Dec are funct on prototypes

    Define funct on bod es

    Ca funct ons

    Dea w th oca and g oba var ab e scope

    Define and use over oaded funct ons

    By now, you shou d be fa r y comfortab e w th bas c C++/CLI syntax Youve seen how to dec are var ab es, wr te statements, use operators, and perform s mp e conso e output However, as your programs beg n to grow arger, you need to organ ze your code to cope w th the grow ng comp ex ty

    In th s chapter, you earn how to d v de a C++/CLI app cat on nto funct ons F rst, you see how to dec are funct on prototypes to ntroduce the funct ons to the comp er Next, you see how to define funct on bod es to carry out the requ red process ng For examp e, you m ght wr te a funct on to ca cu ate the expected growth on an nvestment or to extract the users password from a ogon screen F na y, you see how to ca a funct on from e sewhere n your app cat on

    Why use functions?There are many good reasons for d v d ng an app cat on nto funct ons Here are three of them

    Each funct on s usua y qu te short and d screte Its eas er to wr te an app cat on as a ser es of funct ons than as a s ng e, ong scr pt because you can concentrate on one func-t on at a t me

    Its a so eas er to read and debug an app cat on that conta ns ots of sma funct ons than one that conta ns a s ng e, ong funct on because you dont have to remember what the ent re app cat on s do ng

    Funct ons are reusab e After youve wr tten a funct on, you can ca t whenever you need t n your app cat on, wh ch reduces cod ng effort and therefore mproves deve oper product v ty

  • 38 Microsoft Visual C++/CLI Step by Step

    Declaring function prototypes

    A funct on prototype s a s ng e- ne statement that ntroduces the name of a funct on to the com-p er The prototype a so nd cates what types of parameters can be passed nto the funct on and what type of va ue the funct on returns The comb nat on of nformat on about a funct ons name and parameters s ca ed the function signature

    Declaring a simple function prototypeThe fo ow ng examp e shows a s mp e funct on prototype

    void DisplayWelcome();

    In th s examp e, the name of the funct on s DisplayWelcome The parentheses are requ red to nd -cate that th s s a funct on The parentheses are empty n th s examp e, wh ch means that the funct on doesnt take any parameters The void keyword at the beg nn ng of the funct on prototype nd cates that the funct on doesnt return a va ue; presumab y, the funct on just d sp ays a we come message on the screen

    Note Some programming languages differentiate between functions (which return a value) and subroutines (which do not return a value). For example, Microsoft Visual Basic .NET uses the Function keyword for functions and the Sub keyword for subroutines. C++ only has functions; use the void return type if the function doesnt return a value. Also, notice the semicolon at the end of the function prototype. The semicolon is a statement terminator, and it marks the end of the function prototype. A function prototype doesnt give you any indication as to what the function does; it just provides the function signature.

    a note on function namingSome anguages have very strong nam ng convent ons that gu de how you shou d construct funct on and var ab e names C++ has never had such a un versa convent on, but f youre wr t ng C++/CLI code, you wou d be w se to adopt the convent on used n the M crosoft NET brar es Funct on names shou d start w th a cap ta etter, and nd v dua words w th n the name

    shou d a so be cap ta zed, as n DisplayWelcome or CreateNewCustomerOrder The except on to th s convent on s the entry po nt main, wh ch s trad t ona y typed n owercase etters

    In th s exerc se, you w dec are a s mp e funct on prototype n a C++/CLI app cat on The funct on does not take any parameters, and t does not return a va ue, e ther

    1. Start V sua Stud o 2012 and create a new CLR Conso e App cat on project named InvestmentPlanner

    After the project s created, the source fi e appears n the ed tor w ndow

  • CHAPTER 4 Us ng funct ons 39

    2. At the top of the fi e, mmed ate y be ow the using namespace System; ne, add the fo ow ng funct on prototype

    void DisplayWelcome();

    Th s ne s the funct on prototype you saw ear er You p ace funct on prototypes near the top of the source fi e so that they are v s b e to the rest of the code n the fi e

    3. On the Bu d menu, c ck Bu d So ut on to bu d your app cat on and check that there are no syntax errors

    Theres no po nt n runn ng the app cat on yet because you havent mp emented or ca ed the DisplayWelcome funct on You do that ater n th s chapter

    Declaring parameters in a function prototypeFunct ons can take parameters to make them more gener c You must dec are the data types for these parameters n the funct on prototype

    In th s exerc se, you w dec are a funct on prototype that uses parameters

    1. Cont nue work ng w th the project you created n the prev ous exerc se

    2. Add the fo ow ng funct on prototype mmed ate y be ow the void DisplayWelcome() ne

    void DisplayProjectedValue(double amount, int years, double rate);

    Th s funct on prototype dec ares a funct on named DisplayProjectedValue The funct on takes three parameters a double, an int, and another double The comp er uses th s nformat on to ensure that the funct on s a ways ca ed w th the correct number and types of parameters

    Tip Parameter names are optional in the function prototype. Strictly speaking, you could omit the parameter names and just specify the parameter types. However, pa-rameter names help to convey the meaning of the parameters, so its good practice to use them.

    3. Bu d your app cat on to check the syntax

    Declaring the return type in a function prototypeAs we as spec fy ng nput parameters for a funct on, you must a so spec fy a return type for the func-t on As you saw ear er, the void return type nd cates that the funct on does not return a va ue

    In th s exerc se, you w see how to spec fy a non-void return type for a funct on

    1. Cont nue work ng w th the project from the prev ous exerc se

    2. Add the fo ow ng funct on prototype mmed ate y be ow the void DisplayProjectedValue() ne

    double GetInvestmentAmount();

  • 40 Microsoft Visual C++/CLI Step by Step

    Th s funct on prototype dec ares a funct on named GetInvestmentAmount The funct on doesnt take any parameters, but t returns a doub e

    3. Add another funct on prototype as fo ows, mmed ate y be ow the double GetInvestment Amount() ne

    int GetInvestmentPeriod(int min, int max);

    Th s examp e shows how to dec are a funct on that takes parameters and returns a va ue The GetInvestmentPeriod funct on takes two int parameters and returns an int

    Note The parameter types and return type are independent of one another. The fact that the GetInvestmentPeriod parameters and return type are all ints is entirely coincidental. Its quite easy to imagine a function whose parameter types and return type are different, as shown in this example:

    double CalculateAverageValue(int number1, int number2);

    4. Bu d your app cat on

    Declaring default values for function parametersWhen you dec are a funct on prototype, you can spec fy defau t va ues for some or a of ts parame-ters Defau t va ues are usefu for parameters t