Ivor Horton's
Beginning
Visual C++®2008
Ivor Horton
Wiley Publishing, Inc.
Ivor Horton's
Beginning
Visual C++®2008
Ivor Horton
Wiley Publishing, Inc.
Ivor Horton's Beginning Visual C++®2008
Ivor Horton
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2008 by Ivor Horton
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada ISBN:
978-0-470-22590-5
Library of Congress Cataloging-in-Publication Data is available from the publisher.
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 Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, 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 Website 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 Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites 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 (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
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 in the United States and/or other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
This book is dedicated to Isabella Williams, who joined the growing band of beautiful girls in my life in January 2007.
About the Autuor
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 being usually 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 of the 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 to manufacturing operations in a variety of industries. He has considerable experience developing occasionally useful applications in a wide variety of programming languages, and teaching primarily scientists and engineers to do likewise. He has been writing books on programming for more than 10 years now, 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 trying to speak better French.
Credits
Executive Editor
Robert Elliott
Development Editor
Ed Connor
Technical Editor
John Mueller
Copy Editor
Mildred Sanchez
Editorial Manager
Mary Beth Wakefield
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Joseph B. Wikert
Project Coordinator, Cover
Lynsey Stanford
Compositor
Laurie Stewart, Happenstance Type-O-Rama
Proofreaders
Jeremy Bagai
Sheilah Ledwidge
Carrie Hunter
Lee Ewert
Will DeRooy
Indexer
Jack Lewis
Acknowledgments
Introduction
Chapter 1: Programming with Visual c++ 2008
The .NET Framework
The Common Language Runtime (CLR)
Writing C++ Applications
Learning Windows Programming
Learning C++
The C++ Standards
Attributes
Console Applications
Windows Programming Concepts
What Is the Integrated Development Environment?
Components of the System
Using the IDE
Toolbar Options
Dockable Toolbars
Documentation
Projects and Solutions
Setting Options in Visual C++ 2008
Creating and Executing Windows Applications
Creating a Windows Forms Application
Summary
Chapter 2: Data, Variables, and Calculations
The Structure of a C++ Program
The main() Function
Program Statements
Whitespace
Statement Blocks
Automatically Generated Console Programs
Defining Variables
Naming Variables
Declaring Variables
Initial Values for Variables
Fundamental Data Types
Integer Variables
Character Data Types
Integer Type Modifiers
The Boolean Type
Floating-Point Types
Literals
Defining Synonyms for Data Types
Variables with Specific Sets of Values
Basic Input/Output Operations
Input from the Keyboard
Output to the Command Line
Formatting the Output
Escape Sequences
Calculating in C++
The Assignment Statement
Arithmetic Operations
Calculating a Remainder
Modifying a Variable
The Increment and Decrement Operators
The Sequence of Calculation
Variable Types and Casting
Rules for Casting Operands
Casts in Assignment Statements
Explicit Casts
Old-Style Casts
The Bitwise Operators
The Bitwise AND
The Bitwise OR
The Bitwise Exclusive OR
The Bitwise NOT
The Bitwise Shift Operators
Understanding Storage Duration and Scope
Automatic Variables
Positioning Variable Declarations
Global Variables
Static Variables
Namespaces
Declaring a Namespace
Multiple Namespaces
C++/CLI Programming
C++/CLI Specific: Fundamental Data Types
C++/CLI Output to the Command Line
C++/CLI Specific—Formatting the Output
C++/CLI Input from the Keyboard
Using safe_cast
C++/CLI Enumerations
Summary
Exercises
Chapter 3: Decisions and Loops
Comparing Values
The if Statement
Nested if Statements
Nested if-else Statements
Logical Operators and Expressions
The Conditional Operator
The switch Statement
Unconditional Branching
Repeating a Block of Statements
What Is a Loop?
Variations on the for Loop
The while Loop
The do-while Loop
Nested Loops
C++/CLI Programming
The for each Loop
Summary
Exercises
Chapter 4: Arrays, Strings, and Pointers
Handling Multiple Data Values of the Same Type
Arrays
Declaring Arrays
Initializing Arrays
Character Arrays and String Handling
Multidimensional Arrays
Indirect Data Access
What Is a Pointer?
Declaring Pointers
Using Pointers
Initializing Pointers
The sizeof Operator
Constant Pointers and Pointers to Constants
Pointers and Arrays
Dynamic Memory Allocation
The Free Store, Alias the Heap
The new and delete Operators
Allocating Memory Dynamically for Arrays
Dynamic Allocation of Multidimensional Arrays
Using References
What Is a Reference?
Declaring and Initializing References
Native C++ Library Functions for Strings
Finding the Length of a Null-Terminated String
Joining Null-Terminated Strings
Copying Null-Terminated Strings
Comparing Null-Terminated Strings
Searching Null-Terminated Strings
C++/CLI Programming
Tracking Handles
CLR Arrays
Strings
Tracking References
Interior Pointers
Summary
Exercises
Chapter 5: Introducing Structure into Your Programs
Understanding Functions
Why Do You Need Functions?
Structure of a Function
Using a Function
Function Prototypes
Passing Arguments to a Function
The Pass-by-value Mechanism
Pointers as Arguments to a Function
Passing Arrays to a Function
References as Arguments to a Function
Use of the const Modifier
Arguments to main()
Accepting a Variable Number of Function Arguments
Returning Values from a Function
Returning a Pointer
Static Variables in a Function
Recursive Function Calls
Using Recursion
C++/CLI Programming
Functions Accepting a Variable Number of Arguments
Arguments to main()
Summary
Exercises
Chapter 6: More about Program Structure
Pointers to Functions
Declaring Pointers to Functions
A Pointer to a Function as an Argument
Arrays of Pointers to Functions
Initializing Function Parameters
Exceptions
Throwing Exceptions
Catching Exceptions
Exception Handling in the MFC
Handling Memory Allocation Errors
Function Overloading
What Is Function Overloading?
When to Overload Functions
Function Templates
Using a Function Template
An Example Using Functions
Implementing a Calculator
Eliminating Blanks from a String
Evaluating an Expression
Getting the Value of a Term
Analyzing a Number
Putting the Program Together
Extending the Program
Extracting a Substring
Running the Modified Program
C++/CLI Programming
Understanding Generic Functions
A Calculator Program for the CLR
Summary
Exercises
Chapter 7: Defining Your Own Data Types
The struct in C++
What Is a struct?
Defining a struct
Initializing a struct
Accessing the Members of a struct
IntelliSense Assistance with Structures
The struct RECT
Using Pointers with a struct
Data Types, Objects, Classes, and Instances
First Class
Operations on Classes
Terminology
Understanding Classes
Defining a Class
Declaring Objects of a Class
Accessing the Data Members of a Class
Member Functions of a Class
Positioning a Member Function Definition
Inline Functions
Class Constructors
What Is a Constructor?
The Default Constructor
Assigning Default Parameter Values in a Class
Using an Initialization List in a Constructor
Private Members of a Class
Accessing private Class Members
The friend Functions of a Class
The Default Copy Constructor
The Pointer this
const Objects of a Class
const Member Functions of a Class
Member Function Definitions Outside the Class
Arrays of Objects of a Class
Static Members of a Class
Static Data Members of a Class
Static Function Members of a Class
Pointers and References to Class Objects
Pointers to Class Objects
References to Class Objects
C++/CLI Programming
Defining Value Class Types
Defining Reference Class Types
Defining a Copy Constructor for a Reference Class Type
Class Properties
initonly Fields
Static Constructors
Summary
Exercises
Chapter 8: More on Classes
Class Destructors
What Is a Destructor?
The Default Destructor
Destructors and Dynamic Memory Allocation
Implementing a Copy Constructor
Sharing Memory Between Variables
Defining Unions
Anonymous Unions
Unions in Classes and Structures
Operator Overloading
Implementing an Overloaded Operator
Implementing Full Support for a Comparison Operator
Overloading the Assignment Operator
Overloading the Addition Operator
Overloading the Increment and Decrement Operators
Class Templates
Defining a Class Template
Creating Objects from a Class Template
Class Templates with Multiple Parameters
Using Classes
The Idea of a Class Interface
Defining the Problem
Implementing the CBox Class
Organizing Your Program Code
Naming Program Files
Native C++ Library Classes for Strings
Creating String Objects
Concatenating Strings
Accessing and Modifying Strings
Comparing Strings
Searching Strings
C++/CLI Programming
Overloading Operators in Value Classes
Overloading the Increment and Decrement Operators
Overloading Operators in Reference Classes
Implementing the Assignment Operator for Reference Types
Summary
Exercises
Chapter 9: Class Inheritance and Virtual Functions
Basic Ideas of OOP
Inheritance in Classes
What Is a Base Class?
Deriving Classes from a Base Class
Access Control Under Inheritance
Constructor Operation in a Derived Class
Declaring Class Members to Be Protected
The Access Level of Inherited Class Members
The Copy Constructor in a Derived Class
Class Members as Friends
Friend Classes
Limitations on Class Friendship
Virtual Functions
What Is a Virtual Function?
Using Pointers to Class Objects
Using References with Virtual Functions
Pure Virtual Functions
Abstract Classes
Indirect Base Classes
Virtual Destructors
Casting Between Class Types
Nested Classes
C++/CLI Programming
Boxing and Unboxing
Inheritance in C++/CLI Classes
Interface Classes
Defining Interface Classes
Classes and Assemblies
Functions Specified as new
Delegates and Events
Destructors and Finalizers in Reference Classes
Generic Classes
Summary
Exercises
Chapter 10: The Standard Template Library
What Is the Standard Template Library?
Containers
Container Adapters
Iterators
Algorithms
Function Objects
Function Adapters
The Range of STL Containers
Sequence Containers
Creating Vector Containers
The Capacity and Size of a Vector Container
Accessing the Elements in a Vector
Inserting and Deleting Elements in a Vector
Storing Class Objects in a Vector
Sorting Vector Elements
Storing Pointers in a Vector
Double-Ended Queue Containers
Using List Containers
Using Other Sequence Containers
Associative Containers
Using Map Containers
Using a Multimap Container
More on Iterators
Using Input Stream Iterators
Using Inserter Iterators
Using Output Stream Iterators
More on Function Objects
More on Algorithms
fill()
replace()
find()
transform()
The STL for C++/CLI Programs
STL/CLR Containers
Using Sequence Containers
Using Associative Containers
Summary
Exercises
Chapter 11: Debugging Techniques
Understanding Debugging
Program Bugs
Common Bugs
Basic Debugging Operations
Setting Breakpoints
Setting Tracepoints
Starting Debugging
Changing the Value of a Variable
Adding Debugging Code
Using Assertions
Adding Your Own Debugging Code
Debugging a Program
The Call Stack
Step Over to the Error
Testing the Extended Class
Finding the Next Bug
Debugging Dynamic Memory
Functions Checking the Free Store
Controlling Free Store Debug Operations
Free Store Debugging Output
Debugging C++/CLI Programs
Using the Debug and Trace Classes
Getting Trace Output in Windows Forms Applications
Summary
Chapter 12: Windows Programming Concepts
Windows Programming Basics
Elements of a Window
Windows Programs and the Operating System
Event-Driven Programs
Windows Messages
The Windows API
Windows Data Types
Notation in Windows Programs
The Structure of a Windows Program
The WinMain() Function
Message Processing Functions
A Simple Windows Program
Windows Program Organization
The Microsoft Foundation Classes
MFC Notation
How an MFC Program Is Structured
The Application Class
The Window Class
Completing the Program
The Finished Product
Using Windows Forms
Summary
Chapter 13: Windows Programming with the Microsoft Foundation Classes
The Document/View Concept in MFC
What Is a Document?
Document Interfaces
What Is a View?
Linking a Document and Its Views
Your Application and MFC
Creating MFC Applications
Creating an SDI Application
The Output from the MFC Application Wizard
Creating an MDI Application
Summary
Exercises
Chapter 14: Working with Menus and Toolbars
Communicating with Windows
Understanding Message Maps
Message Categories
Handling Messages in Your Program
How Command Messages Are Processed
Extending the Sketcher Program
Elements of a Menu
Creating and Editing Menu Resources
Adding a Menu Item to the Menu Bar
Adding Items to the Element Menu
Modifying Existing Menu Items
Completing the Menu
Adding Handlers for Menu Messages
Choosing a Class to Handle Menu Messages
Creating Menu Message Functions
Coding Menu Message Functions
Adding Message Handlers to Update the User Interface
Adding Toolbar Buttons
Editing Toolbar Button Properties
Exercising the Toolbar Buttons
Adding Tooltips
Menu and Toolbars in a C++/CLI Program
Understanding Windows Forms
Understanding Windows Forms Applications
Adding a Menu to CLR Sketcher
Adding Event Handlers for Menu Items
Implementing Event Handlers
Setting Menu Item Checks
Adding a Toolbar
Summary
Exercises
Chapter 15: Drawing in a Window
Basics of Drawing in a Window
The Window Client Area
The Windows Graphical Device Interface
The Drawing Mechanism in Visual C++
The View Class in Your Application
The CDC Class
Drawing Graphics in Practice
Programming the Mouse
Messages from the Mouse
Mouse Message Handlers
Drawing Using the Mouse
Exercising Sketcher
Running the Example
Capturing Mouse Messages
Drawing with the CLR
Drawing on a Form
Adding Mouse Event Handlers
Defining C++/CLI Element Classes
Implementing the MouseMove Event Handler
Implementing the MouseUp Event Handler
Implementing the Paint Event Handler for the Form
Summary
Exercises
Chapter 16: Creating the Document and Improving the View
The MFC Collection Classes
Types of Collection
The Type-Safe Collection Classes
Collections of Objects
The Typed Pointer Collections
Using the CList Template Class
Drawing a Curve
Defining the CCurve Class
Implementing the CCurve Class
Exercising the CCurve Class
Creating the Sketch Document
Using a CTypedPtrList Template
Improving the View
Updating Multiple Views
Scrolling Views
Using MM_LOENGLISH Mapping Mode
Deleting and Moving Shapes
Implementing a Context Menu
Associating a Menu with a Class
Choosing a Context Menu
Highlighting Elements
Servicing the Menu Messages
Dealing with Masked Elements
Extending CLRSketcher
Coordinate System Transformations
Defining a Curve
Defining a Sketch Class
Drawing the Sketch in the Paint Event Handler
Implementing Element Highlighting
Creating Context Menus
Summary
Exercises
Chapter 17: Working with Dialogs and Controls
Understanding Dialogs
Understanding Controls
Common Controls
Creating a Dialog Resource
Adding Controls to a Dialog Box
Programming for a Dialog
Adding a Dialog Class
Modal and Modeless Dialogs
Displaying a Dialog
Supporting the Dialog Controls
Initializing the Controls
Handling Radio Button Messages
Completing Dialog Operations
Adding Pen Widths to the Document
Adding Pen Widths to the Elements
Creating Elements in the View
Exercising the Dialog
Using a Spin Button Control
Adding the Scale Menu Item and Toolbar Button
Creating the Spin Button
Generating the Scale Dialog Class
Displaying the Spin Button
Using the Scale Factor
Scaleable Mapping Modes
Setting the Document Size
Setting the Mapping Mode
Implementing Scrolling with Scaling
Working with Status Bars
Adding a Status Bar to a Frame
Using a List Box
Removing the Scale Dialog
Creating a List Box Control
Using an Edit Box Control
Creating an Edit Box Resource
Creating the Dialog Class
Adding the Text Menu Item
Defining a Text Element
Implementing the CText Class
Creating a Text Element
Dialogs and Controls in CLR Sketcher
Adding a Dialog
Creating Text Elements
Summary
Exercises
Chapter 18: Storing and Printing Documents
Understanding Serialization
Serializing a Document
Serialization in the Document Class Definition
Serialization in the Document Class Implementation
Functionality of CObject-Based Classes
How Serialization Works
How to Implement Serialization for a Class
Applying Serialization
Recording Document Changes
Serializing the Document
Serializing the Element Classes
Exercising Serialization
Moving Text
Printing a Document
The Printing Process
Implementing Multipage Printing
Getting the Overall Document Size
Storing Print Data
Preparing to Print
Cleaning Up After Printing
Preparing the Device Context
Printing the Document
Getting a Printout of the Document
Serialization and Printing in CLR Sketcher
Understanding Binary Serialization
Serializing a Sketch
Printing a Sketch
Summary
Exercises
Chapter 19: Writing Your Own DLLs
Understanding DLLs
How DLLs Work
Contents of a DLL
DLL Varieties
Deciding What to Put in a DLL
Writing DLLs
Writing and Using an Extension DLL
Exporting Classes from the Extension DLL
Exporting Variables and Functions from a DLL
Importing Symbols into a Program
Implementing the Export of Symbols from a DLL
Summary
Exercises
Chapter 20: Connecting to Data Sources
Database Basics
A Little SQL
Retrieving Data Using SQL
Joining Tables Using SQL
Sorting Records
Database Support in MFC
MFC Classes Supporting ODBC
Creating a Database Application
Registering an ODBC Database
Generating an MFC ODBC Program
Understanding the Program Structure
Exercising the Example
Sorting a Recordset
Modifying the Window Caption
Using a Second Recordset Object
Adding a Recordset Class
Adding a View Class for the Recordset
Viewing Customer Details
Adding the Customer Recordset
Creating the Customer Dialog Resource
Creating the Customer View Class
Adding a Filter
Implementing the Filter Parameter
Linking the Order Dialog to the Customer Dialog
Exercising the Database Viewer
Summary
Exercises
Chapter 21: Updating Data Sources
Update Operations
CRecordset Update Operations
Transactions
A Simple Update Example
Customizing the Application
Managing the Update Process
Implementing Update Mode
Adding Rows to a Table
The Order Entry Process
Creating the Resources
Creating the Recordsets
Creating the Recordset Views
Adding Controls to the Dialog Resources
Implementing Dialog Switching
Creating an Order ID
Storing the Order Data
Selecting Products for an Order
Adding a New Order
Summary
Exercises
Chapter 22: More on Windows Forms Applications
Creating the Application GUI
Adding Submenus
Adding a Tab Control
Using GroupBox Controls
Using Button Controls
Using the WebBrowser Control
Operation of the Winning Application
Adding a Context Menu
Creating Event Handlers
Handling Events for the Limits Menu
Creating a Dialog Box
Using the Dialog Box
Adding the Second Dialog
Implementing the Help > About Menu Item
Handling a Button Click
Responding to the Context Menu
Summary
Exercises
Chapter 23: Accessing Data Sources in a Windows Forms Application
Working with Data Sources
Accessing and Displaying Data
Using a DataGridView Control
Using a DataGridView Control in Unbound Mode
Customizing a DataGridView Control
Customizing Header Cells
Customizing Non-Header Cells
Setting Up the Data
Setting Up the Control
Setting Up the Column Headers
Formatting a Column
Customizing Alternate Rows
Dynamically Setting Cell Styles
Using Bound Mode
The BindingSource Component
Using the BindingNavigator Control
Binding to Individual Controls
Working with Multiple Tables
Summary
Exercises
Acknowledgments
I'd like to acknowledge the efforts and support of the John Wiley & Sons and Wrox Press editorial and production team in the production of this book, especially my development editor, Ed Connor, who has been there from way back at the beginning and has stayed through to the end. I'd also like to thank my technical editor, John Mueller, once again for doing such an outstanding job of reviewing the text and checking out all the examples in the book; his many constructive comments undoubtedly helped make the book a much better tutorial.
As always, the love and support of my wife, Eve, have been fundamental to making it possible for me to write this book. She has pandered to my every need throughout and has remained patient and cheerful in spite of the hours I spend locked away in my office and my intermittent grumblings about the workload I imposed upon myself.
Ivor Hortons
Beginning Visual C++®2008
Introduction
Chapter 1: Programming with Visual C++ 2008
Chapter 2: Data, Variables, and Calculations
Chapter 3: Decisions and Loops
Chapter 4: Arrays, Strings, and Pointers
Chapter 5: Introducing Structure into Your Programs
Chapter 6: More about Program Structure
Chapter 7: Defining Your Own Data Types
Chapter 8: More on Classes
Chapter 9: Class Inheritance and Virtual Functions
Chapter 10: The Standard Template Library
Chapter 11: Debugging Techniques
Chapter 12: Windows Programming Concepts
Chapter 13: Windows Programming with the Microsoft Foundation Classes
Chapter 14: Working with Menus and Toolbars
Chapter 15: Drawing in a Window
Chapter 16: Creating the Document and Improving the View
Chapter 17: Working with Dialogs and Controls
Chapter 18: Storing and Printing Documents
Chapter 19: Writing Your Own DLLs
Chapter 20: Connecting to Data Sources
Chapter 21: Updating Data Sources
Chapter 22: More on Windows Forms Applications
Chapter 23: Accessing Data Sources in a Windows Forms Application
Appendix A: C++ Keywords
Appendix B: ASCII Codes
Appendix C: Windows Message Types
Introduction
Welcome to Beginning Visual C++® 2008. With this book you can become an effective C++ programmer. The latest development system from Microsoft, Visual Studio 2008, supports two distinct but closely related flavors of the C++ language; it fully supports the original ISO/ANSI standard C++, and you also get support for a new version of C++ called C++/CLI that was developed by Microsoft and is now an ECMA standard. These two versions of C++ are complementary and fulfill different roles. ISO/ANSI C++ is there for the development of high-performance applications that run natively on your computer whereas C++/CLI has been developed specifically for writing applications that target the .NET Framework. This book will teach you how to write applications in both versions of C++.
You get quite a lot of assistance from automatically generated code when writing ISO/ANSI C++ programs, but you still need to write a lot of C++ yourself. You need a solid understanding of object-oriented programming techniques, as well as a good appreciation of what's involved in programming for Windows. Although C++/CLI targets the .NET Framework, it also is the vehicle for the development of Windows Forms applications that you can develop with little or in some cases no explicit code writing. Of course, when you do have to add code to a Windows Forms application, even though it may be a very small proportion of the total, you still need an in-depth knowledge of the C++/CLI language. ISO/ANSI C++ remains the language of choice for many professionals, but the speed of development that C++/CLI and Windows Forms applications bring to the table make that essential, too. For this reason I cover both flavors of C++ in this book.
Whom This Book Is For
This book is aimed at teaching you how to write C++ applications for the Microsoft Windows operating system using Visual C++ 2008 or any edition of Visual Studio 2008. I make no assumptions about prior knowledge of any particular programming language. This tutorial is for you if:
What This Book Covers
My objective with this book is to teach you the essentials of C++ programming using both of the technologies supported by Visual C++ 2008. The book provides a detailed tutorial on both flavors of the C++ language, on native ISO/ANSI C++ Windows application development using the Microsoft Foundation Classes (MFC), and on the development of C++/CLI Windows applications using Windows Forms.
Because of the importance and pervasiveness of database technology today, the book also includes introductions to the techniques you can use for accessing data sources in both MFC and Windows Forms applications. MFC applications are relatively coding-intensive compared to Windows Forms applications. This is because you create the latter using a highly developed design capability in Visual C++ 2008 that enables you to assemble the entire graphical user interface (GUI) for an application graphically and have all the code that creates it generated automatically. For this reason, there are more pages in the book devoted to MFC programming than to Windows Forms programming.
How This Book Is Structured
The contents of this book are structured as follows:
All chapters include numerous working examples that demonstrate the programming techniques that are 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 Web site (see the “Source Code” section later in this Introduction for more details).
The tutorial on the C++ language uses examples that are console programs with simple command-line input and output. This approach enables you to learn the various capabilities of C++ without getting bogged down in the complexities of Windows GUI programming. Programming for Windows is really only practicable after you have a thorough understanding of the programming language.
If you want to keep things as simple as possible, you can just learn ISO/ANSI C++ programming in the first instance. Each of the chapters that cover the C++ language (Chapters 2 to 9) first discusses particular aspects of the capabilities of ISO/ANSI C++, followed by the new features introduced by C++/CLI in the same context. The reason for organizing things this way is that C++/CLI is defined as an extension to the ISO/ANSI standard language, so an understanding of C++/CLI is predicated on knowledge of ISO/ANSI C++. Thus, you can just read the ISO/ANSI topics in each of Chapters 2 to 9 and ignore the C++/CLI sections that follow. You then can progress to Windows application development with ISO/ANSI C++ without having to keep the two versions of the language in mind. You can return to C++/CLI when you are comfortable with ISO/ANSI C++. Of course, you can also work straight through and add to your knowledge of both versions of the C++ language incrementally.
What You Need to Use This Book
To use this book you need any of Visual Studio 2008 Standard Edition, Visual Studio 2008 Professional Edition, or Visual Studio 2008 Team System. Note that Visual C++ Express 2008 is not sufficient because the MFC is not included.
Visual Studio 2008 requires Windows XP (x86 or x64) with Service Pack 2 or later, Windows Server 2003 with Service Pack 1 or later, or any edition of Windows Vista except Starter Edition. To install any of the three Visual Studio 2008 editions identified you need to have a 1.6 GHz processor with at least 384MB of memory (at least 768MB for Windows Vista) and at least 2.2GB of hard-disk space available. To install the full MSDN documentation that comes with the product you'll need an additional 1.8GB available on the installation drive.
The database examples in the book use the Northwind Traders database. You can find the download for this database by searching for “Northwind Traders” on http://msdn.microsoft.com. Of course, you can also adapt the examples to work with a database of your choice.
Most importantly, to get the most out of this book you need a willingness to learn, and a determination to master the most powerful programming tool for Windows applications presently available. You need the dedication to type in and work through all the examples and try out the exercises in the book. This sounds more difficult than it is, and I think you'll be surprised how much you can achieve in a relatively short period of time. Keep in mind that everybody who learns programming gets bogged down from time to time, but if you keep at it, things become clearer and you'll get there eventually. This book helps you to start experimenting on your own and, from there, to become a successful C++ programmer.
Using the Windows Classic Theme
If you're working in Windows Vista with Visual Studio 2008, you may have noticed that the view looks amazing. The transparency offered by the Aero Glass interface is quite breathtaking at first glance (and even many glances afterward). When you add in all of the visual effects that Vista has to offer, you might wonder why anyone would object to such a nice work environment. However, after a few hours of watching windows bursting forth and seeing the display dazzle your vision, you may prefer a setting that is less likely to cause eye fatigue. More importantly, you may notice a significant drop in your productivity because all of this eye candy robs your system of important processing cycles.
Eye candy is nice, but isn't it nicer to get home on time after a long day writing code? That's one reason why this book uses the Windows Classic theme to show Visual Studio 2008 windows. Another reason is that if you are still using Windows XP, the fancy Vista windows would not mean very much to you. The Windows Classic theme is common to both operating systems so it will fit with whatever operating system you are using, and it's definitely friendlier to your eyes than the Aero Glass interface.
If you are using Vista, I encourage you to try the various themes that Vista offers to see if they work for you. However, if you'd like to use the same theme in Vista as I have used for this book, then you can follow these steps to obtain it.
1. Right-click the Desktop and choose Personalize from the context menu. The Personalize window is shown in Figure I-1. This window provides access to all of the display settings you need to obtain the Windows Classic view.
Figure I-1
2. Click Theme to display the Theme Settings dialog box shown in Figure I-2.
Figure I-2
3. Choose Windows Classic in the Theme field and click OK. At this point, your display will begin looking very much like mine. Of course, you still have all of those special effects to consider. The next set of steps will get rid of the special effects.
4. Close the Personalize window.
5. Open the System applet in the Control Panel to display the System window shown in Figure I-3.
Figure I-3
6. Click Advanced System Settings to display the Advanced tab of the System Properties dialog box shown in Figure I-4.
Figure I-4
7. Click Settings in the Performance area to display the Performance Options dialog box shown in Figure I-5.
Figure I-5
8. Choose the Adjust for Best Performance option as shown in Figure I-5. Click OK twice to close both dialog boxes. At this point, your system is adjusted to provide the same view that I'm using and also for best graphic performance.
You may also want to use the Classic Start menu to make it easier to locate applications and to perform other tasks. To set your system up for the Classic Start menu, right-click the taskbar and choose Properties. Select the Start menu tab. Choose the Classic Start menu option, make any required customizations by clicking Customize, and click OK. You now have an optimal environment for working with Visual Studio.
Of course, if you are using Windows XP and you want your screen images to look like those in the book, you can use the Classic theme here, too. Just right-click on the Windows desktop, and select Properties from the pop-up menu to display the dialog shown in Figure I-6.
On the Themes tab in the Display Properties dialog, select Windows Classic from the drop-down list of themes. Click the OK button and you are in business.
Figure I-6
Conventions
To help you get the most from the text and keep track of what's happening, a number of conventions are used throughout the book.
Try It Out
The Try It Out is an exercise involving a working example you should create, compile, and execute, following the text in the book. Output from a working example is shown in a monospaced font like this:
Here is output from the example. Here is more output!
How It Works
After each Try It Out, the code you've typed is explained in detail in a How It Works section.
Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
Monofont type with no highlighting is used for code that you have seen before or for code that was
created automatically for you.
Gray highlighting is used to show code that's new or modified.
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. All of the source code used in this book is available for download at http://www.wrox.com. At the site, simply locate the book's title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book's detail page to obtain all the source code for the book.
While just using the downloaded code is an option, I strongly recommend that you type the code for examples manually and only turn to the code download as a last resort. This will not only be very effective in helping you learn and remember the language syntax, but will also give you valuable experience in making and hopefully correcting mistakes in your code.
Because many books have similar titles, you may find it easiest to search by ISBN; this book's ISBN is 978-0-470-22590-5.
After you download the code, just decompress it with your favorite compression tool. Alternatively, you can go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
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 details 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.
You can read messages in the forums without joining P2P but in order to post your own messages, you must join.
After 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.