Ivor Horton's Beginning Visual C++ 2012 - Ivor Horton - E-Book

Ivor Horton's Beginning Visual C++ 2012 E-Book

Ivor Horton

0,0
38,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The only book to teach C++ programming with Microsoft Visual Studio! There's a reason why Ivor Horton's Beginning Visual C++ books dominate the marketplace. Ivor Horton has a loyal following who love his winning approach to teaching programming languages, and in this fully updated new edition, he repeats his successful formula. Offering a comprehensive introduction to both the standard C++ language and to Visual C++, he offers step-by-step programming exercises, examples, and solutions to deftly guide novice programmers through the ins and outs of C++ development. * Introduces novice programmers to the current standard, Microsoft Visual C++ 2012, as it is implemented in Microsoft Visual Studio 2012 * Focuses on teaching both the C++11 standard and Visual C++ 2012, unlike virtually any other book on the market * Covers the C++ language and library and the IDE * Delves into new features of both the C++11 standard and of the Visual C++ 2012 programming environment * Features C++ project templates, code snippets, and more Even if you have no previous programming experience, you'll soon learn how to build real-world applications using Visual C++ 2012 with this popular guide.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 1611

Veröffentlichungsjahr: 2012

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



CONTENTS

Cover

Contents

Title page

Copyright

Dedication

ABOUT THE AUTHOR

ABOUT THE TECHNICAL EDITOR

CREDITS

ACKNOWLEDGMENTS

INTRODUCTION

WHO THIS BOOK IS FOR

WHAT THIS BOOK COVERS

HOW THIS BOOK IS STRUCTURED

WHAT YOU NEED TO USE THIS BOOK

CONVENTIONS

SOURCE CODE

EXERCISES

ERRATA

P2P.WROX.COM

Chapter 1: Programming with Visual C++

LEARNING WITH VISUAL C++

WRITING C++ APPLICATIONS

LEARNING DESKTOP APPLICATIONS PROGRAMMING

WHAT IS THE INTEGRATED DEVELOPMENT ENVIRONMENT?

USING THE IDE

SUMMARY

Chapter 2: Data, Variables, and Calculations

THE STRUCTURE OF A C++ PROGRAM

DEFINING VARIABLES

FUNDAMENTAL DATA TYPES

BASIC INPUT/OUTPUT OPERATIONS

CALCULATING IN C++

TYPE CONVERSION AND CASTING

THE AUTO KEYWORD

DISCOVERING TYPES

THE BITWISE OPERATORS

INTRODUCING LVALUES AND RVALUES

UNDERSTANDING STORAGE DURATION AND SCOPE

VARIABLES WITH SPECIFIC SETS OF VALUES

NAMESPACES

SUMMARY

Chapter 3: Decisions and Loops

COMPARING VALUES

REPEATING A BLOCK OF STATEMENTS

SUMMARY

Chapter 4: Arrays, Strings, and Pointers

HANDLING MULTIPLE DATA VALUES OF THE SAME TYPE

INDIRECT DATA ACCESS

DYNAMIC MEMORY ALLOCATION

USING REFERENCES

LIBRARY FUNCTIONS FOR STRINGS

SUMMARY

Chapter 5: Introducing Structure into Your Programs

UNDERSTANDING FUNCTIONS

PASSING ARGUMENTS TO A FUNCTION

RETURNING VALUES FROM A FUNCTION

RECURSIVE FUNCTION CALLS

SUMMARY

Chapter 6: More about Program Structure

POINTERS TO FUNCTIONS

INITIALIZING FUNCTION PARAMETERS

EXCEPTIONS

HANDLING MEMORY ALLOCATION ERRORS

FUNCTION OVERLOADING

FUNCTION TEMPLATES

USING THE DECLTYPE OPERATOR

AN EXAMPLE USING FUNCTIONS

SUMMARY

Chapter 7: Defining Your Own Data Types

THE STRUCT IN C++

TYPES, OBJECTS, CLASSES, AND INSTANCES

UNDERSTANDING CLASSES

CLASS CONSTRUCTORS

PRIVATE MEMBERS OF A CLASS

THE POINTER THIS

CONST OBJECTS

ARRAYS OF OBJECTS

STATIC MEMBERS OF A CLASS

POINTERS AND REFERENCES TO OBJECTS

SUMMARY

Chapter 8: More on Classes

CLASS DESTRUCTORS

IMPLEMENTING A COPY CONSTRUCTOR

SHARING MEMORY BETWEEN VARIABLES

OPERATOR OVERLOADING

THE OBJECT COPYING PROBLEM

DEFAULT CLASS MEMBERS

CLASS TEMPLATES

PERFECT FORWARDING

USING CLASSES

ORGANIZING YOUR PROGRAM CODE

LIBRARY CLASSES FOR STRINGS

SUMMARY

Chapter 9: Class Inheritance and Virtual Functions

OBJECT-ORIENTED PROGRAMMING BASICS

INHERITANCE IN CLASSES

ACCESS CONTROL UNDER INHERITANCE

THE COPY CONSTRUCTOR IN A DERIVED CLASS

PREVENTING CLASS DERIVATION

CLASS MEMBERS AS FRIENDS

VIRTUAL FUNCTIONS

CASTING BETWEEN CLASS TYPES

NESTED CLASSES

SUMMARY

Chapter 10: The Standard Template Library

WHAT IS THE STANDARD TEMPLATE LIBRARY?

SMART POINTERS

ALGORITHMS

FUNCTION OBJECTS IN THE STL

FUNCTION ADAPTERS

THE RANGE OF STL CONTAINERS

SEQUENCE CONTAINERS

ASSOCIATIVE CONTAINERS

MORE ON ITERATORS

MORE ON FUNCTION OBJECTS

MORE ON ALGORITHMS

TYPE TRAITS AND STATIC ASSERTIONS

LAMBDA EXPRESSIONS

SUMMARY

Chapter 11: Windows Programming Concepts

WINDOWS PROGRAMMING BASICS

THE STRUCTURE OF A WINDOWS PROGRAM

THE MICROSOFT FOUNDATION CLASSES

SUMMARY

Chapter 12: Windows Programming with the Microsoft Foundation Classes (MFC)

THE MFC DOCUMENT/VIEW CONCEPT

CREATING MFC APPLICATIONS

SUMMARY

Chapter 13: Working with Menus and Toolbars

COMMUNICATING WITH WINDOWS

EXTENDING THE SKETCHER PROGRAM

ELEMENTS OF A MENU

ADDING MENU MESSAGE HANDLERS

ADDING TOOLBAR BUTTONS

SUMMARY

Chapter 14: Drawing in a Window

BASICS OF DRAWING IN A WINDOW

THE MFC DRAWING MECHANISM

DRAWING GRAPHICS IN PRACTICE

PROGRAMMING FOR THE MOUSE

DRAWING A SKETCH

SUMMARY

Chapter 15: Improving the View

SKETCHER LIMITATIONS

IMPROVING THE VIEW

DELETING AND MOVING ELEMENTS

IMPLEMENTING A CONTEXT MENU

IDENTIFYING AN ELEMENT UNDER THE CURSOR

DEALING WITH MASKED ELEMENTS

SUMMARY

Chapter 16: Working with Dialogs and Controls

UNDERSTANDING DIALOGS

UNDERSTANDING CONTROLS

CREATING A DIALOG RESOURCE

PROGRAMMING FOR A DIALOG

SUPPORTING THE DIALOG CONTROLS

COMPLETING DIALOG OPERATIONS

USING A SPIN BUTTON CONTROL

USING THE SCALE FACTOR

WORKING WITH STATUS BARS

THE CSTRING CLASS

USING AN EDIT BOX CONTROL

SUMMARY

Chapter 17: Storing and Printing Documents

UNDERSTANDING SERIALIZATION

SERIALIZING A DOCUMENT

APPLYING SERIALIZATION

EXERCISING SERIALIZATION

PRINTING A DOCUMENT

IMPLEMENTING MULTIPAGE PRINTING

SUMMARY

Chapter 18: Programming Windows 8 Apps

UNDERSTANDING WINDOWS 8 APPS

DEVELOPING WINDOWS 8 APPS

WINDOWS RUNTIME CONCEPTS

C++ COMPONENT EXTENSIONS (C++/CX)

THE EXTENSIBLE APPLICATION MARKUP LANGUAGE (XAML)

CREATING A WINDOWS 8 APP

SCALING UI ELEMENTS

TRANSITIONS

SUMMARY

Backcover

Related Wrox Books

End User License Agreement

List of Illustrations

Chapter 01

FIGURE 1-1

FIGURE 1-2

FIGURE 1-3

FIGURE 1-4

FIGURE 1-5

FIGURE 1-6

FIGURE 1-7

FIGURE 1-8

FIGURE 1-9

FIGURE 1-10

FIGURE 1-11

FIGURE 1-12

FIGURE 1-13

FIGURE 1-14

FIGURE 1-15

Chapter 02

FIGURE 2-1

FIGURE 2-2

FIGURE 2-3

FIGURE 2-4

FIGURE 2-5

FIGURE 2-6

FIGURE 2-7

FIGURE 2-8

FIGURE 2-9

FIGURE 2-10

FIGURE 2-11

Chapter 03

FIGURE 3-1

FIGURE 3-2

FIGURE 3-3

FIGURE 3-4

FIGURE 3-5

FIGURE 3-6

Chapter 04

FIGURE 4-1

FIGURE 4-2

FIGURE 4-3

FIGURE 4-4

FIGURE 4-5

FIGURE 4-6

FIGURE 4-7

FIGURE 4-8

Chapter 05

FIGURE 5-1

FIGURE 5-2

FIGURE 5-3

FIGURE 5-4

Chapter 06

FIGURE 6-1

FIGURE 6-2

FIGURE 6-3

FIGURE 6-4

FIGURE 6-5

FIGURE 6-6

FIGURE 6-7

FIGURE 6-8

Chapter 07

FIGURE 7-1

FIGURE 7-2

FIGURE 7-3

FIGURE 7-4

FIGURE 7-5

FIGURE 7-6

FIGURE 7-7

Chapter 08

FIGURE 8-1

FIGURE 8-2

FIGURE 8-3

FIGURE 8-4

FIGURE 8-5

FIGURE 8-6

FIGURE 8-7

FIGURE 8-8

FIGURE 8-9

FIGURE 8-10

FIGURE 8-11

FIGURE 8-12

Chapter 09

FIGURE 9-1

FIGURE 9-2

FIGURE 9-3

FIGURE 9-4

FIGURE 9-5

FIGURE 9-6

Chapter 10

FIGURE 10-1

FIGURE 10-2

FIGURE 10-3

FIGURE 10-4

Chapter 11

FIGURE 11-1

FIGURE 11-2

FIGURE 11-3

FIGURE 11-4

FIGURE 11-5

Chapter 12

FIGURE 12-1

FIGURE 12-2

FIGURE 12-3

FIGURE 12-4

FIGURE 12-5

FIGURE 12-6

FIGURE 12-7

FIGURE 12-8

FIGURE 12-9

FIGURE 12-10

FIGURE 12-11

FIGURE 12-12

FIGURE 12-13

Chapter 13

FIGURE 13-1

FIGURE 13-2

FIGURE 13-3

FIGURE 13-4

FIGURE 13-5

FIGURE 13-6

FIGURE 13-7

FIGURE 13-8

FIGURE 13-9

FIGURE 13-10

FIGURE 13-11

FIGURE 13-12

FIGURE 13-13

FIGURE 13-14

Chapter 14

FIGURE 14-1

FIGURE 14-2

FIGURE 14-3

FIGURE 14-4

FIGURE 14-5

FIGURE 14-6

FIGURE 14-7

FIGURE 14-8

FIGURE 14-9

FIGURE 14-10

FIGURE 14-11

FIGURE 14-12

FIGURE 14-13

FIGURE 14-14

FIGURE 14-15

FIGURE 14-16

FIGURE 14-17

Chapter 15

FIGURE 15-1

FIGURE 15-2

FIGURE 15-3

FIGURE 15-4

Chapter 16

FIGURE 16-1

FIGURE 16-2

FIGURE 16-3

FIGURE 16-4

FIGURE 16-5

FIGURE 16-6

FIGURE 16-7

FIGURE 16-8

FIGURE 16-9

FIGURE 16-10

FIGURE 16-11

FIGURE 16-12

FIGURE 16-13

FIGURE 16-14

FIGURE 16-15

FIGURE 16-16

Chapter 17

FIGURE 17-1

FIGURE 17-2

FIGURE 17-3

FIGURE 17-4

FIGURE 17-5

FIGURE 17-6

FIGURE 17-7

FIGURE 17-8

FIGURE 17-9

Chapter 18

FIGURE 18-1

FIGURE 18-2

FIGURE 18-3

FIGURE 18-4

FIGURE 18-5

FIGURE 18-6

FIGURE 18-7

FIGURE 18-8

FIGURE 18-9

FIGURE 18-10

Pages

v

vi

vii

ix

xi

xiii

xv

xxxv

xxxvi

xxxvii

xxxviii

xxxix

xl

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

944

945

946

Guide

Cover

Table of Contents

IVOR HORTON’S BEGINNING

Visual C++® 2012

Ivor Horton

Ivor Horton’s Beginning Visual C++® 2012

Published byJohn Wiley & Sons, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

Copyright © 2012 by Ivor Horton

Published by John Wiley & Sons, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-1-118-36808-4ISBN: 978-1-118-43941-8 (ebk)ISBN: 978-1-118-41703-4 (ebk)ISBN: 978-1-118-43431-4 (ebk)

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.

Library of Congress Control Number: 2012946046

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Visual C++ is a registered trademark of Microsoft Corporation. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

This book is for my dear wife, Eve, who for so many years has given me unconditional support and love in whatever I choose to do. I could not have written this without her.

ABOUT THE AUTHOR

IVOR HORTON graduated as a mathematician and was lured into information technology by promises of great rewards for very little work. In spite of the reality usually being a great deal of work for relatively modest rewards, he has continued to work with computers to the present day. He has been engaged at various times in programming, systems design, consultancy, and the management and implementation of projects of considerable complexity.

Horton has many years of experience in the design and implementation of computer systems applied to engineering design and manufacturing operations in a variety of industries. He has considerable experience in developing occasionally useful applications in a wide variety of programming languages, and in teaching primarily scientists and engineers to do likewise. He has been writing books on programming for many years, and his currently published works include tutorials on C, C++, and Java. At the present time, when he is not writing programming books or providing advice to others, he spends his time fishing, traveling, and enjoying life in general.

ABOUT THE TECHNICAL EDITOR

MARC GREGOIRE is a software engineer from Belgium. He graduated from the Catholic University of Leuven, Belgium, with a degree in “Burgerlijk ingenieur in de computer wetenschappen” (equivalent to master of science in engineering in computer science). The year after, he received the cum laude degree of master in artificial intelligence at the same university. After his studies, Marc started working for a big software consultancy company called Ordina Belgium. As a consultant, he worked for Siemens and Nokia Siemens Networks on critical 2G and 3G software running on Solaris for big telecom operators. This required working in international teams stretching from South America and USA to EMEA and Asia. Now, Marc is working for Nikon Metrology on 3D scanning software.

His main expertise is C/C++, and specifically Microsoft VC++ and the MFC framework. Next to C/C++, Marc also likes C# and uses PHP for creating web pages. In addition to his main interest for Windows development, he also has experience in developing C++ programs running 24/7 on Linux platforms; for example, EIB home automation-controlling and monitoring software.

Since April 2007, he received the yearly Microsoft MVP (Most Valuable Professional) award for his Visual C++ expertise.

Marc is the founder of the Belgian C++ Users Group (www.becpp.org) and an active member on the CodeGuru forum (as Marc G). He also creates freeware and shareware programs that are distributed through his website at www.nuonsoft.com, and maintains a blog on www.nuonsoft.com/blog/.

CREDITS

Executive Editor

Robert Elliott

Project Editor

Ed Connor

Technical Editor

Marc Gregoire

Production Editor

Daniel Scribner

Copy Editor

Kim Cofer

Editorial Manager

Mary Beth Wakefield

Freelancer Editorial Manager

Rosemarie Graham

Associate Director of Marketing

David Mayhew

Marketing Manager

Ashley Zurcher

Business Manager

Amy Knies

Production Manager

Tim Tate

Vice President and Executive Group Publisher

Richard Swadley

Vice President and Executive Publisher

Neil Edde

Associate Publisher

Jim Minatel

Project Coordinator, Cover

Katie Crocker

Proofreaders

James Saturnio, Word One

Sarah Kaikini, Word One

Indexer

Ron Strauss

Cover Designer

Ryan Sneed

Cover Image

© Kyu Oh / iStockPhoto

ACKNOWLEDGMENTS

THE AUTHOR IS ONLY ONE MEMBER of the large team of people necessary to get a book into print. I’d like to thank the John Wiley & Sons and Wrox Press editorial and production teams for their help and support throughout.

I would particularly like to thank my technical editor, Marc Gregoire, for doing such a fantastic job of reviewing the text and checking out all the code fragments and examples. He has an uncanny knack for finding my errors, and his many constructive comments and suggestions have undoubtedly made the book a much better tutorial.

INTRODUCTION

WELCOME TOIvor Horton’s Beginning Visual C++ 2012. With this book, you can become an effective C++ programmer using Microsoft’s latest application-development system, Visual Studio 2012. I aim to teach you the C++ programming language, and then how to apply C++ in the development of your own Windows applications. Along the way, you will also learn about many of the exciting new capabilities introduced by this latest version of Visual C++.

Visual C++ 2012 comes as part of any of the editions of the Microsoft development environment Visual Studio 2012. When I refer to Visual C++ in the rest of the book, I mean the Visual C++ 2012 capability that comes as part of Visual Studio 2012.

WHO THIS BOOK IS FOR

This book is for anyone who wants to learn how to write C++ applications for the Microsoft Windows operating system using Visual C++. I make no assumptions about prior knowledge of any particular programming language, so there are no prerequisites other than some aptitude for programming and sufficient enthusiasm and commitment for learning to program in C++ to make it through this book. This tutorial is for you if:

You are a newcomer to programming and sufficiently keen to jump into the deep end with C++. To be successful, you need to have at least a rough idea of how your computer works, and it will be helpful if you understand the way in which the memory is organized and how data and instructions are stored.

You have a little experience of programming in some other language, such as BASIC, and you are keen to learn C++ and develop practical Microsoft Windows programming skills.

You have some experience in C or C++, but not in a Microsoft Windows context and want to extend your skills to program for the Windows environment using the latest tools and technologies.

WHAT THIS BOOK COVERS

The first part of the book teaches you the essentials of C++ programming using the C++ language supported by Visual Studio 2012 through a detailed, step-by-step tutorial. You’ll learn the syntax and use of the ISO/IEC C++ language and gain experience and confidence in applying it in a practical context through an extensive range of working examples. There are also exercises that you can use to test your knowledge, with solutions available for download if you get stuck.

Of course, the language tutorial also introduces and demonstrates the use of the C++ standard library facilities you are most likely to need. You’ll add to your knowledge of the standard libraries incrementally as you progress through the C++ language. Additionally, you will learn about the powerful tools provided by the Standard Template Library (STL).

Once you are confident in applying C++, you move on to Windows programming. You will learn how to develop Windows applications using the Microsoft Foundation Classes (MFC) by creating a substantial working application of more than 2000 lines of code. You develop the application over several chapters, utilizing a broad range of user interface capabilities provided by the MFC. You also learn the essentials of programming applications using the Windows 8 UI and develop a working example.

HOW THIS BOOK IS STRUCTURED

The book is structured as follows:

Chapter 1 introduces you to the basic concepts you need to understand for programming in C++ together with the main ideas embodied in the Visual C++ development environment. It describes how you use the capabilities of Visual C++ for creating the various kinds of C++ applications you’ll learn about in the rest of the book.

Chapters 2 through 9 teach you the C++ language. You start with simple procedural program examples and progress to learning about classes and object-oriented programming.

Chapter 10 teaches you how you use the Standard Template Library (STL). The STL is a powerful and extensive set of tools for organizing and manipulating data in your C++ programs. The STL is application-neutral, so you will be able to apply it in a wide range of contexts.

Chapter 11 discusses how Microsoft Windows desktop applications are structured and describes and demonstrates the essential elements that are present in every desktop application written for the Windows operating system. The chapter explains elementary examples of how Windows applications work, with programs that use C++ with the Windows API and with the MFC.

Chapters 12 through 17 teach you Windows desktop application programming. You learn to write C++ Windows applications using the MFC for building a GUI. You learn how you create and use common controls to build the graphical user interface for your application, and how you handle the events that result from user interaction with your program. In addition to the techniques you learn for building a GUI, the application that you develop also shows you how you handle printing and how you can save your application data on disk.

Chapter 18 introduces the fundamental ideas involved in writing applications for Windows 8.

All chapters in the book include working examples that demonstrate the programming techniques discussed. Every chapter concludes with a summary of the key points that were covered, and most chapters include a set of exercises at the end that you can attempt, to apply what you have learned. Solutions to the exercises, together with all the code from the book, are available for download from the publisher’s website.

WHAT YOU NEED TO USE THIS BOOK

There are several versions of Visual Studio 2012 and they each have a different range of capabilities. You can only develop applications using the Windows 8 UI if you have Visual Studio 2012 installed with Windows 8. Here’s what you can use to work with various parts of the book:

If you have a free version of Visual Studio 11 installed with Windows 8, you can work with all the examples and exercises in the book. The lowest-cost fee version of Visual Studio 2012 is the Professional Edition. This edition or better installed with Windows 8 is fine for the whole book.

If you have Visual Studio 2012 Professional Edition or better installed with Windows 7, you can work with all the examples and exercises in Chapters 1 to 17, but not Chapter 18. Chapter 18 is about applications that make use of the Windows 8 UI and this requires Visual Studio 2012 to be installed with Windows 8.

There is a free Visual Studio 2012 Express Edition for Windows 8, which is not sufficient to run many of the examples in the book. None of the examples in Chapters 12 to 17 can be compiled with the Visual Studio 2012 Express Edition.

CONVENTIONS

To help you get the most from the text and keep track of what’s happening, we’ve used a number of conventions throughout the book.

TRY IT OUT

The Try It Out is an exercise you should work through, following the text in the book.

1

. They usually consist of a set of steps.

2

. Each step has a number.

3

. Follow the steps through with your copy of the program.

How It Works

After each Try It Out, the code you’ve typed will be explained in detail.

WARNINGBoxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.

NOTENotes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

We

highlight

new terms and important words when we introduce them.

We show keyboard strokes like this: Ctrl+A.

We show filenames, URLs, and code within the text like so:

persistence.properties

.

We present code in two different ways:

We use a monofont type with no highlighting for most code examples.

We use bold highlighting to emphasize code that is of particular importance in the present context.

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually, or to use the source code files that accompany the book. The code downloads for the complete examples in the book are located at www.wrox.com/remtitle.cgi?isbn=9781118368084 on the Download Code tab.

NOTEBecause many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-111-36808-4.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

EXERCISES

Many of the chapters have a set of exercises for you to test your knowledge. I encourage you to try all of these. If you get stuck you can download solutions to all of these exercises from www.wrox.com/remtitle.cgi?isbn=9781118368084.

ERRATA

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information.

To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book’s detail page, click the Book Errata link. On this page, you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

P2P.WROX.COM

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com, you will find a number of different forums that will help you, not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1

. Go to

p2p.wrox.com

and click the Register link.

2

. Read the terms of use and click Agree.

3

. Complete the required information to join, as well as any optional information you wish to provide, and click Submit.

4

. You will receive an e-mail with information describing how to verify your account and complete the joining process.

NOTEYou can read messages in the forums without joining P2P, but in order to post your own messages, you must join.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

Chapter 1Programming with Visual C++

WHAT YOU WILL LEARN IN THIS CHAPTER:

What the principal components of Visual C++ are

What solutions and projects are and how you create them

About console programs

How to create and edit a program

How to compile, link, and execute C++ console programs

How to create and execute basic Windows programs

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

You can find the wrox.com code downloads for this chapter on the Download Code tab at www.wrox.com/remtitle.cgi?isbn=9781118368084. The code is in the Chapter 1 download and individually named according to the names throughout the chapter.

LEARNING WITH VISUAL C++

Windows programming isn’t difficult. Microsoft Visual C++ makes it remarkably easy, as you’ll see throughout the course of this book. There’s just one obstacle in your path: Before you get to the specifics of Windows programming, you have to be thoroughly familiar with the capabilities of the C++ programming language, particularly the object-oriented capabilities. Object-oriented techniques are central to the effectiveness of all the tools provided by Visual C++ for Windows programming, so it’s essential that you gain a good understanding of them. That’s exactly what this book provides.

This chapter gives you an overview of the essential concepts involved in programming applications in C++. You’ll take a rapid tour of the integrated development environment (IDE) that comes with Visual C++. The IDE is straightforward and generally intuitive in its operation, so you’ll be able to pick up most of it as you go along. The best way to get familiar with it is to work through the process of creating, compiling, and executing a simple program. So power up your PC, start Windows, load the mighty Visual C++, and begin your journey.

WRITING C++ APPLICATIONS

You have tremendous flexibility in the types of applications and program components that you can develop with Visual C++. Applications that you can develop fall into two broad categories: desktop applications and Windows 8 apps. Desktop applications are the applications that you know and love; they have an application window that typically has a menu bar and a toolbar and frequently a status bar at the bottom of the application window. This book focuses primarily on desktop applications.

Windows 8 apps are different from desktop applications. They have a user interface that is completely different from desktop applications. The focus is on the content where the user interacts directly with the data, rather than interacting with controls such as menu items and toolbar buttons.

Once you have learned C++, this book concentrates on using the Microsoft Foundation Classes (MFC) with C++ for building desktop applications. The application programming interface (API) for Windows desktop applications is referred to as Win32. Win32 has a long history and was developed long before the object-oriented programming paradigm emerged, so it has none of the object-oriented characteristics that would be expected if it were written today. The MFC consists of a set of C++ classes that encapsulate the Win32 API for user interface creation and control and greatly eases the process of program development. You are not obliged to use the MFC, though. If you want the ultimate in performance you can write your C++ code to access the Windows API directly, but it certainly won’t be as easy.

Figure 1-1 shows the basic options you have for developing C++ applications.

FIGURE 1-1

Figure 1-1 is a simplified representation of what is involved. Desktop applications can target Windows 7, Windows 8, or Windows Vista. Windows 8 apps execute only with Windows 8 and you must have Visual Studio 2012 installed under Windows 8 to develop them. Windows 8 apps communicate with the operating system through the Windows Runtime, WinRT. I’ll introduce you to programming Windows 8 applications in Chapter 18.

LEARNING DESKTOP APPLICATIONS PROGRAMMING

There are always two basic aspects to interactive desktop applications executing under Windows: You need code to create the graphical user interface (GUI) with which the user interacts, and you need code to process these interactions to provide the functionality of the application. Visual C++ provides you with a great deal of assistance in both aspects. As you’ll see later in this chapter, you can create a working Windows program with a GUI without writing any code at all. All the basic code to create the GUI can be generated automatically by Visual C++. Of course, it’s essential to understand how this automatically generated code works because you need to extend and modify it to make the application do what you want. To do that you need a comprehensive understanding of C++.

For this reason you’ll first learn C++ without getting involved in Windows programming considerations. After you’re comfortable with C++ you’ll learn how to develop fully fledged Windows applications. This means that while you are learning C++, you’ll be working with programs that involve only command line input and output. By sticking to this rather limited input and output capability, you’ll be able to concentrate on the specifics of how the C++ language works and avoid the inevitable complications involved in GUI building and control. Once you are comfortable with C++ you’ll find that it’s an easy and natural progression to applying C++ to the development of Windows application programs.

NOTEAs I’ll explain in Chapter 18, Windows 8 apps are different. You specify the GUI in XAML, and the XAML is used to generate the C++ program code for GUI elements.

Learning C++

Visual C++ supports the C++ language defined by the most recent ISO/IEC C++ standard that was published in 2011. The standard is defined in the document ISO/IEC 14882:2011 and commonly referred to as C++ 11. The Visual C++ compiler does not support all the new language features introduced by this latest standard, just some of the most commonly used features, but it will surely be extended over time. Programs that you write in standard C++ can be ported from one system environment to another reasonably easily, although the library functions that a program uses — particularly those related to building a graphical user interface — are a major determinant of how easy or difficult it will be. ISO/IEC standard C++ is the first choice of a great many professional program developers because it is so widely supported, and because it is one of the most powerful programming languages available today.

Chapters 2 through 9 of this book teach you the C++ language and introduce some of the most commonly used C++ standard library facilities along the way. Chapter 10 explains how you can use the Standard Template Library (STL) for C++ for managing collections of data.

Console Applications

Visual C++ console applications enable you to write, compile, and test C++ programs that have none of the baggage required for Windows programs. These programs are called console applications because you communicate with them through the keyboard and the screen in character mode, so they are essentially character-based, command-line programs.

When you write console applications, it might seem as if you are being sidetracked from the main objective of programming applications for Windows, but when it comes to learning C++ it’s by far the best way to proceed in my view. There’s a lot of code in even a simple Windows program, and it’s very important not to be distracted by the complexities of Windows when learning the ins and outs of the C++ language. In the early chapters of the book that are concerned with how C++ works, you’ll spend time walking with a few lightweight console applications before you get to run with the heavyweight sacks of code in the world of Windows.

Windows Programming Concepts

The project creation facilities provided with Visual C++ can generate skeleton code for a wide variety of C++ application programs automatically. A Windows program has a different structure from that of the typical console program that you execute from the command line and it’s more complicated. In a console program you can get user input from the keyboard and write output back to the command line directly, and that is essentially it. A Windows application can access the input and output facilities of the computer only by way of functions supplied by the host environment; no direct access to the hardware resources is permitted. Several programs can be active at one time under Windows, so the operating system has to determine which application a given raw input such as a mouse click or the pressing of a key on the keyboard is destined for, and signal the program concerned accordingly. Thus, the Windows operating system always has primary control of all communications with the user.

The nature of the interface between a user and a Windows desktop application is such that a wide range of different inputs is usually possible at any given time. A user may select any of a number of menu options, click on one of several toolbar buttons, or click the mouse somewhere in the application window. A well-designed Windows application has to be prepared to deal with any of the possible types of input at any time because there is no way of knowing in advance which type of input is going to occur. These user actions are received by the operating system in the first instance, and are all regarded by Windows as events. An event that originates with the user interface for your application will typically result in a particular piece of your program code being executed. How program execution proceeds is therefore determined by the sequence of user actions. Programs that operate in this way are referred to as event-driven programs, and are different from traditional procedural programs that have a single order of execution. Input to a procedural program is controlled by the program code and can occur only when the program permits it; therefore, a Windows program consists primarily of pieces of code that respond to events caused by the action of the user, or by Windows itself. This sort of program structure is illustrated in Figure 1-2.

FIGURE 1-2

Each block within the Desktop Application block in Figure 1-2 represents a piece of code written specifically to deal with a particular event. The program may appear to be somewhat fragmented because of the disjointed blocks of code, but the primary factor welding the program into a whole is the Windows operating system itself. You can think of your program as customizing Windows to provide a particular set of capabilities.

Of course, the modules servicing external events such as the selection of a menu or a mouse click, all typically have access to a common set of application-specific data in a particular program. This data contains information that relates to what the program is about — for example, blocks of text recording scoring records for a player in a program aimed at tracking how your baseball team is doing — as well as information about some of the events that have occurred during execution of the program. This shared collection of data allows various parts of the program that look independent to communicate and operate in a coordinated and integrated fashion. I will go into this in much more detail later in the book.

Even an elementary Windows program involves several lines of code, and with Windows programs generated by the application wizards that come with Visual C++, “several” turns out to be “very many.” To simplify the process of understanding how C++ works, you need a context that is as uncomplicated as possible and at the same time has the tools to make it easy to navigate around sacks of code. Fortunately, Visual C++ comes with an environment that is designed specifically for the purpose.

WHAT IS THE INTEGRATED DEVELOPMENT ENVIRONMENT?

The integrated development environment (IDE) that comes with Visual C++ is a completely self-contained environment for creating, compiling, linking, and testing your C++ programs. It also happens to be a great environment in which to learn C++ (particularly when combined with a great book).

Visual C++ incorporates a range of fully integrated tools designed to make the whole process of writing C++ programs easy. You will see something of these in this chapter, but rather than grind through a boring litany of features and options in the abstract, you can first take a look at the basics to get a view of how the IDE works and then pick up the rest in context as you go along.

The fundamental parts of Visual C++, provided as part of the IDE, are the editor, the compiler, the linker, and the libraries. These are the basic tools that are essential to writing and executing a C++ program.

The Editor

The editor provides an interactive environment in which to create and edit C++ source code. As well as the usual facilities, such as cut and paste, which you are certainly already familiar with, the editor also provides color cues to differentiate between various language elements. The editor automatically recognizes fundamental words in the C++ language and assigns a color to them according to what they are. This not only helps to make your code more readable, but also provides a clear indicator of when you make errors in keying such words. Another very helpful feature is IntelliSense. IntelliSense analyzes the code as you enter it, and underlines anything that is incorrect with a red squiggle. It can also provide prompts where the options for what you need to enter next in the code can be determined.

NOTEIntelliSense doesn’t just work with C++. It works with XAML too.

The Compiler

You execute the compiler when you have entered the C++ code for your program. The compiler converts your source code into object code, and detects and reports errors in the compilation process. The compiler can detect a wide range of errors caused by invalid or unrecognized program code, as well as structural errors, such as parts of a program that can never be executed. The object code output from the compiler is stored in files called object files that have names with the extension .obj.

The Linker

The linker combines the various modules generated by the compiler from source code files, adds required code modules from program libraries that are supplied as part of C++, and welds everything into an executable whole, usually in the form of an .exe file. The linker can also detect and report errors — for example, if part of your program is missing, or a nonexistent library component is referenced.

The Libraries

A library is simply a collection of prewritten routines that supports and extends the C++ language by providing standard professionally produced code units that you can incorporate into your programs to carry out common operations. The operations implemented by the various libraries provided by Visual C++ greatly enhance productivity by saving you the effort of writing and testing the code for such operations yourself.

The Standard C++ Library defines a basic set of facilities that are common to all ISO/IEC standard-conforming C++ compilers. It contains a wide range of commonly used routines, including numerical functions, such as the calculation of square roots and the evaluation of trigonometrical functions; character- and string-processing functions, such as the classification of characters and the comparison of character strings; and many others. It also defines data types and standard templates for generating customized data types and functions. You’ll get to know quite a number of these as you develop your knowledge of C++.

Window-based desktop applications are supported by a library called the Microsoft Foundation Classes (MFC). The MFC greatly reduces the effort needed to build the GUI for an application. (You’ll see a lot more of the MFC when you finish exploring the nuances of the C++ language.)

USING THE IDE

All program development and execution in this book is performed from within the IDE. When you start Visual C++ you’ll see an application window similar to that shown in Figure 1-3.

FIGURE 1-3

The pane to the left in Figure 1-3 is the Solution Explorer window, the top right pane presently showing the Start page is the Editor window, and the tab visible in the pane at the bottom is the Output window. The Solution Explorer window enables you to navigate through your program files and display their contents in the Editor window, and to add new files to your program. The Solution Explorer window can display other tabs (only three are shown in Figure 1-3), and you can select which tabs are to be displayed from the View menu. The Editor window is where you enter and modify source code and other components of your application. The Output window displays the output from build operations in which a project is compiled and linked. You can choose to display other windows by selecting from the View menu.

Note that a window can generally be undocked from its position in the Visual C++ application window. Just right-click the title bar of the window you want to undock and select Float from the pop-up menu. In general, I will show windows in their undocked state in the book. You can restore a window to its docked state by right-clicking its title bar and selecting Dock from the pop-up or by dragging it with the left mouse button down to the position that you want in the application window.

Toolbar Options

You can choose which toolbars are displayed in your Visual C++ window by right-clicking in the toolbar area. The range of toolbars in the list depends on which edition of Visual Studio 2012 you have installed. A pop-up menu with a list of toolbars (Figure 1-4) appears, and the toolbars currently displayed have checkmarks alongside them.

FIGURE 1-4

This is where you decide which toolbars are visible at any one time. You can make your set of toolbars the same as those shown in Figure 1-3 by making sure the Build, Debug, Formatting, Layout, Standard, and Text Editor menu items are selected. Clicking a toolbar in the list checks it if it is deselected, and results in its being displayed; clicking a toolbar that is selected/deselects it and hides the toolbar.

NOTEA toolbar won’t necessarily display all the buttons that are available for it. You can add or remove buttons for a toolbar by clicking the down arrow that appears at the right of the button set. The buttons in the TextEditor toolbar that indent and unindent a set of highlighted statements are particularly useful, as are the buttons that comment out or uncomment a highlighted set of statements.

You don’t need to clutter up the application window with all the toolbars you think you might need at some time. Some toolbars appear automatically when required, so you’ll probably find that the default toolbar selections are perfectly adequate most of the time. As you develop your applications, from time to time you might think it would be more convenient to have access to toolbars that aren’t displayed. You can change the set of visible toolbars whenever it suits you by right-clicking in the toolbar area and choosing from the context menu.

NOTEAs in many other Windows applications, the toolbars that make up Visual C++ come complete with tooltips. Just let the mouse pointer linger over a toolbar button for a second or two, and a white label will display the function of that button.

Dockable Toolbars

A dockable toolbar is one that you can move around to position it at a convenient place in the window. You can arrange for any of the toolbars to be docked at any of the four sides of the application window. If you right-click in the toolbar area and select Customize from the pop-up, the Customize dialog will be displayed. You can choose where a particular toolbar is docked by selecting it and clicking the Modify Selection button. You can then choose from the drop-down list to dock the toolbar where you want. Figure 1-5 shows how the dialog looks after the user selects the Build toolbar on the left and clicks the Modify Selection drop-down list.

FIGURE 1-5

You’ll recognize many of the toolbar icons that Visual C++ uses from other Windows applications, but you may not appreciate exactly what these icons do in the context of Visual C++, so I’ll describe them as we use them.

Because you’ll use a new project for every program you develop, looking at what exactly a project is and understanding how the mechanism for defining a project works is a good place to start finding out about Visual C++.

Documentation

There will be plenty of occasions when you’ll want to find out more information about Visual C++ and its features and options. Press Ctrl+F1 to access the product documentation. With the cursor on elements in your code that are part of the C++ language or a standard library item, pressing F1 will usually open browser window showing documentation for the element. The Help menu also provides various routes into the documentation, as well as access to program samples and technical support.

Projects and Solutions

A project is a container for all the things that make up a program of some kind — it might be a console program, a window-based program, or some other kind of program — and it usually consists of one or more source files containing your code, plus possibly other files containing auxiliary data. All the files for a project are stored in the project folder; detailed information about the project is stored in an XML file with the extension .vcxproj, also in the project folder. The project folder also contains other folders that are used to store the output from compiling and linking your project.

The idea of a solution