Sams Teach Yourself C++ in 21 Days

Sams Teach Yourself C++ in 21 Days

by Jesse Liberty

Paperback(Older Edition)

$29.23 $34.99 Save 16% Current price is $29.23, Original price is $34.99. You Save 16%. View All Available Formats & Editions

Temporarily Out of Stock Online

Eligible for FREE SHIPPING


Sams Teach Yourself C++ in 21 Days by Jesse Liberty

Join the leagues of thousands of programmers and learn C++ from some of the best. The fifth edition of the best seller Sams Teach Yourself C++ in 21 Days, written by Jesse Liberty, a well-known C++ and C# programming manual author and Bradley L. Jones, manager for a number of high profiler developer websites, has been updated to the new ANSI/ISO C++ Standard. This is an excellent hands-on guide for the beginning programmer. Packed with examples of syntax and detailed analysis of code, fundamentals such as managing I/O, loops, arrays and creating C++ applications are all covered in the 21 easy-to-follow lessons. You will also be given access to a website that will provide you will all the source code examples developed in the book as a practice tool. C++ is the preferred language for millions of developers-make Sams Teach Yourself the preferred way to learn it!

Product Details

ISBN-13: 9780672320729
Publisher: Pearson Education
Publication date: 03/15/2001
Series: Sams Teach Yourself Series
Edition description: Older Edition
Pages: 885
Product dimensions: 7.30(w) x 9.20(h) x 2.01(d)

About the Author

Jesse Liberty is the author of numerous books on software development, including best-selling titles in C++ and .NET. He is the president of Liberty Associates, Inc. ( where he provides custom programming, consulting, and training.

Bradley Jones, Microsoft MVP, Visual C++, can be referred to as a webmaster, manager, coding grunt, executive editor, and various other things. His time and focus are on a number of software development sites and channels, including,, DevX, VBForums, Gamelan, and other Jupitermedia-owned sites. This influence expands over sites delivering content to over 2.5 million unique developers a month.

His expertise is in the area of the big "C"s–C, C++, and C#–however, his experience includes development in PowerBuilder, VB, some Java, ASP, COBOL I/II, and various other technologies too old to even mention now. He has also been a consultant, analyst, project lead, associate publisher for major technical publishers, and author. His recent authoring credits include Sams Teach Yourself the C# Language in 21 Days, a 6th edition of Sams Teach Yourself C in 21 Days, and now this edition of Sams Teach Yourself C++ in 21 Days. He is also the cofounder and president of the Indianapolis .NET Developers Association, which is a charter INETA group with membership of over 700. You can often hear his ramblings on the or discussion forums, and he also does the weekly CodeGuru newsletter that goes out to tens of thousands of developers.

Read an Excerpt

Chapter 1: Getting Started


Welcome to Sams Teach Yourself C++ in 21 Days! Today you will get started on your way to becoming a proficient C++ programmer.

Today you will learn

  • Why C++ is the emerging standard in software development.
  • The steps to develop a C++ program.
  • How to enter, compile, and link your first working C++ program.

A Brief History of C++

Computer languages have undergone dramatic evolution since the first electronic computers were built to assist in artillery trajectory calculations during World War II. Early on, programmers worked with the most primitive computer instructions: machine language. These instructions were represented by long strings of ones and zeros. Soon. assemblers were invented to nap machine instructions to human-readable and -manageable mnemonics, such as ADD and MOV.

In time, higher-level languages evolved, such as BASIC and COBOL. These languages let people work with something approximating words and sentences, such as Let I = 100. These instructions were translated back into machine language by interpreters and compilers.

An interpreter translates a program as it reads it, turning the program instructions, or code, directly into actions. A compiler translates the code into an intermediary form. This step is called compiling, and it produces an object file. The compiler then invokes a linker, which turns the object file into an executable program.

Because interpreters read the code as it is written and execute the code on the spot, interpreters are easy for the programmer to work with. Today, most interpreted programs are referred to as scripts, and the interpreter itself is often called a Script Engine.

Some languages, such as Visual Basic, call the interpreter the runtime library. .lava calls its runtime interpreter a Virtual Machine (VM), but in this case the VM is provided by the browser (such as Internet Explorer or Netscape).

Compilers introduce the extra steps of compiling the source code (which is readable by humans) into object code (which is readable by machines). This extra step is inconvenient, but compiled programs run very fast because the time-consuming task of translating the source code into machine language is done once (at compile time) and is not required when you execute the program. Another advantage of many compiled languages such as C++ is that you can distribute the executable program to people who don't have the compiler. With an interpreted ]an

For many years, the principal goal of computer programmers was to write short pieces of code that would execute quickly. The program needed to be small because memory was expensive, and it needed to be fast because processing power was also expensive. As computers have become smaller, cheaper, and faster, and as the cost of memory has fallen, these priorities have changed. Today the cost of a programmers time far outweighs the cost of most of the computers in use by businesses. Well-written, easy-to-maintain code is at a premium. Easy to maintain means that as business requirements change, the program can be extended and enhanced without great expense...

Table of Contents


Who Should Read This Book

Conventions Used in This Book

Sample Code for This Book

Week 1 At a Glance

A Note to C Programmers

Where You Are Going

1. Getting Started.

A Brief History of C++

The Need for Solving Problems

Procedural, Structured, and Object-Oriented Programming

Object-Oriented Programming (OOP)

C++ and Object-Oriented Programming

How C++ Evolved

Should I Learn C First?

C++, Java, and C#

Microsoft's Managed Extensions to C++

The ANSI Standard

Preparing to Program

Your Development Environment

The Process of Creating the Program

Creating an Object File with the Compiler

Creating an Executable File with the Linker

The Development Cycle

HELLO.cpp-Your First C++ Program

Getting Started with Your Compiler

Building the Hello World Project

Compile Errors






2. The Anatomy of a C++ Program.

A Simple Program

A Brief Look at cout

Using the Standard Namespace

Commenting Your Programs

Types of Comments

Using Comments

A Final Word of Caution About Comments


Using Functions

Methods Versus Functions






3. Working with Variables and Constants.

What Is a Variable?

Storing Data in Memory

Setting Aside Memory

Size of Integers

signed and unsigned

Fundamental Variable Types

Defining aVariable

Case Sensitivity

Naming Conventions


Creating More Than One Variable at a Time

Assigning Values to Your Variables

Creating Aliases with typedef

When to Use short and When to Use long

Wrapping Around an unsigned Integer

Wrapping Around a signed Integer

Working with Characters

Characters and Numbers

Special Printing Characters


Literal Constants

Symbolic Constants

Enumerated Constants






4. Creating Expressions and Statements.

Starting with Statements

Using Whitespace

Blocks and Compound Statements


Working with Operators

Assignment Operators

Mathematical Operators

Combining the Assignment and Mathematical Operators

Incrementing and Decrementing

Prefixing Versus Postfixing

Understanding Operator Precedence

Nesting Parentheses

The Nature of Truth

Evaluating with the Relational Operators

The if Statement

Indentation Styles

The else Statement

Advanced if Statements

Using Braces in Nested if Statements

Using the Logical Operators

The Logical AND Operator

The Logical OR Operator

The Logical NOT Operator

Short Circuit Evaluation

Relational Precedence

More About Truth and Falsehood

The Conditional (Ternary) Operator






5. Organizing into Functions.

What Is a Function?

Return Values, Parameters, and Arguments

Declaring and Defining Functions

Function Prototypes

Defining the Function

Execution of Functions

Determining Variable Scope

Local Variables

Local Variables Within Blocks

Parameters Are Local Variables

Global Variables

Global Variables: A Word of Caution

Considerations for Creating Function Statements

More About Function Arguments

More About Return Values

Default Parameters

Overloading Functions

Special Topics About Functions

Inline Functions


How Functions Work-A Peek Under the Hood

Levels of Abstraction






6. Understanding Object-Oriented Programming.

Is C++ Object-Oriented?

Creating New Types

Introducing Classes and Members

Declaring a Class

A Word on Naming Conventions

Defining an Object

Classes Versus Objects

Accessing Class Members

Assigning to Objects, Not to Classes

If You Don't Declare It, Your Class Won't Have It

Private Versus Public Access

Making Member Data Private

Implementing Class Methods

Adding Constructors and Destructors

Getting a Default Constructor and Destructor

Using the Default Constructor

Including const Member Functions

Interface Versus Implementation

Where to Put Class Declarations and Method Definitions

Inline Implementation

Classes with Other Classes as Member Data

Exploring Structures






7. More on Program Flow.


The Roots of Looping: goto

Why goto Is Shunned

Using while Loops

Exploring More Complicated while Statements

Introducing continue and break

Examining while (true) Loops

Implementing do...while Loops

Using do...while

Looping with the for Statement

Advanced for Loops

Empty for Loops

Nesting Loops

Scoping in for Loops

Summing Up Loops

Controlling Flow with switch Statements

Using a switch Statement with a Menu






Week 1 In Review

Week 2 At a Glance

Where You Are Going

8. Understanding Pointers.

What Is a Pointer?

A Bit About Memory

Getting a Variable's Memory Address

Storing a Variable's Address in a Pointer

Pointer Names

Getting the Value from a Variable

Dereferencing with the Indirection Operator

Pointers, Addresses, and Variables

Manipulating Data by Using Pointers

Examining the Address

Why Would You Use Pointers?

The Stack and the Free Store (Heap)

Allocating Space with the new Keyword

Putting Memory Back: The delete Keyword

Another Look at Memory Leaks

Creating Objects on the Free Store

Deleting Objects from the Free Store

Accessing Data Members

Creating Member Data on the Free Store

The this Pointer

Stray, Wild, or Dangling Pointers

Using const Pointers

const Pointers and const Member Functions

Using a const this Pointers






9. Exploiting References.

What Is a Reference?

Using the Address-Of Operator (&) on References

Attempting to Reassign References (Not!)

Referencing Objects

Null Pointers and Null References

Passing Function Arguments by Reference

Making swap() Work with Pointers

Implementing swap() with References

Understanding Function Headers and Prototypes

Returning Multiple Values

Returning Values by Reference

Passing by Reference for Efficiency

Passing a const Pointer

References as an Alternative

Knowing When to Use References Versus Pointers

Mixing References and Pointers

Returning Out-of-Scope Object References

Returning a Reference to an Object on the Heap

Pointer, Pointer, Who Has the Pointer?






10. Working with Advanced Functions.

Overloaded Member Functions

Using Default Values

Choosing Between Default Values and Overloaded Functions

The Default Constructor

Overloading Constructors

Initializing Objects

The Copy Constructor

Operator Overloading

Writing an Increment Function

Overloading the Prefix Operator

Returning Types in Overloaded Operator Functions

Returning Nameless Temporaries

Using the this Pointer

Overloading the Postfix Operator

Difference Between Prefix and Postfix

Overloading Binary Mathematical Operators

Issues in Operator Overloading

Limitations on Operator Overloading

What to Overload

The Assignment Operator

Handling Data Type Conversion

Conversion Operators






11. Object-Oriented Analysis and Design.

Building Models

Software Design: The Modeling Language

Software Design: The Process

Waterfall Versus Iterative Development

The Process of Iterative Development

Step 1: The Conceptualization Phase: Starting with The Vision

Step 2: The Analysis Phase: Gathering Requirements

Use Cases

Application Analysis

Systems Analysis

Planning Documents



Step 3: The Design Phase

What Are the Classes?


Other Transformations

Building the Static Model

Dynamic Model

Steps 4-6: Implementation, Testing, and Rollout?







12. Implementing Inheritance.

What Is Inheritance?

Inheritance and Derivation

The Animal Kingdom

The Syntax of Derivation

Private Versus Protected

Inheritance with Constructors and Destructors

Passing Arguments to Base Constructors

Overriding Base Class Functions

Hiding the Base Class Method

Calling the Base Method

Virtual Methods

How Virtual Functions Work

Trying to Access Methods from a Base Class


Creating Virtual Destructors

Virtual Copy Constructors

The Cost of Virtual Methods






13. Managing Arrays and Strings.

What Is an Array?

Accessing Array Elements

Writing Past the End of an Array

Fence Post Errors

Initializing Arrays

Declaring Arrays

Using Arrays of Objects

Declaring Multidimensional Arrays

Initializing Multidimensional Arrays

Building Arrays of Pointers

A Look at Pointer Arithmetic-An Advanced Topic

Declaring Arrays on the Free Store

A Pointer to an Array Versus an Array of Pointers

Pointers and Array Names

Deleting Arrays on the Free Store

Resizing Arrays at Runtime

char Arrays and Strings

Using the strcpy() and strncpy() Methods

String Classes

Linked Lists and Other Structures

Creating Array Classes






14. Polymorphism.

Problems with Single Inheritance

Percolating Upward

Casting Down

Adding to Two Lists

Multiple Inheritance

The Parts of a Multiply Inherited Object

Constructors in Multiply Inherited Objects

Ambiguity Resolution

Inheriting from Shared Base Class

Virtual Inheritance

Problems with Multiple Inheritance

Mixins and Capabilities Classes

Abstract Data Types

Pure Virtual Functions

Implementing Pure Virtual Functions

Complex Hierarchies of Abstraction

Which Classes Are Abstract?






Week 2 In Review

Week 3 At a Glance

Where You Are Going

15. Special Classes and Functions.

Sharing Data Among Objects of the Same Type: Static Member Data

Using Static Member Functions

Pointers to Functions

Why Use Function Pointers?

Arrays of Pointers to Functions

Passing Pointers to Functions to Other Functions

Using typedef with Pointers to Functions

Pointers to Member Functions

Arrays of Pointers to Member Functions






16. Advanced Inheritance.


Accessing Members of the Aggregated Class

Controlling Access to Aggregated Members

Cost of Aggregation

Copying by Value

Implementation in Terms of Inheritance Versus Aggregation/Delegation

Using Delegation

Private Inheritance

Adding Friend Classes

Friend Functions

Friend Functions and Operator Overloading

Overloading the Insertion Operator






17. Working with Streams.

Overview of Streams

Encapsulation of Data Flow

Understanding Buffering

Streams and Buffers

Standard I/O Objects

Redirection of the Standard Streams

Input Using cin

Inputting Strings

String Problems

The cin Return Value

Other Member Functions of cin

Single Character Input

Getting Strings from Standard Input

Using cin.ignore()

Peeking at and Returning Characters: peek() and putback()

Outputting with cout

Flushing the Output

Functions for Doing Output

Manipulators, Flags, and Formatting Instructions

Streams Versus the printf() Function

File Input and Output

Using the ofstream

Condition States

Opening Files for Input and Output

Changing the Default Behavior of ofstream on Open

Binary Versus Text Files

Command-line Processing






18. Creating and Using Namespaces.

Getting Started

Resolving Functions and Classes by Name

Visibility of Variables


Static Global Variables

Creating a Namespace

Declaring and Defining Types

Defining Functions Outside a Namespace

Adding New Members

Nesting Namespaces

Using a Namespace

The using Keyword

The using Directive

The using Declaration

The Namespace Alias

The Unnamed Namespace

The Standard Namespace std






19. Templates.

What Are Templates?

Building a Template Definition

Using the Name

Implementing the Template

Passing Instantiated Template Objects to Functions

Templates and Friends

Nontemplate Friend Classes and Functions

General Template Friend Class or Function

Using Template Items

Using Specialized Functions

Static Members and Templates

The Standard Template Library

Using Containers

Understanding Sequence Containers

Understanding Associative Containers

Working with the Algorithm Classes






20. Handling Errors and Exceptions.

Bugs, Errors, Mistakes, and Code Rot

Exceptional Circumstances

The Idea Behind Exceptions

The Parts of Exception Handling

Causing Your Own Exceptions

Creating an Exception Class

Placing try Blocks and catch Blocks

How Catching Exceptions Work

Using More Than One catch Specification

Exception Hierarchies

Data in Exceptions and Naming Exception Objects

Exceptions and Templates

Exceptions Without Errors

A Word About Code Rot

Bugs and Debugging


Watch Points

Examining Memory







21. What's Next.

The Preprocessor and the Compiler

The #define Preprocessor Directive

Using #define for Constants

Using #define for Tests

The #else Precompiler Command

Inclusion and Inclusion Guards

Macro Functions

Why All the Parentheses?

String Manipulation



Predefined Macros

The assert() Macro

Debugging with assert()

Using assert() Versus Exceptions

Side Effects

Class Invariants

Printing Interim Values

Inline Functions

Bit Twiddling

Operator AND

Operator OR

Operator Exclusive OR

The Complement Operator

Setting Bits

Clearing Bits

Flipping Bits

Bit Fields

Programming Style



Long Lines and Function Length

Structuring switch Statements

Program Text

Naming Identifiers

Spelling and Capitalization of Names


Setting Up Access

Class Definitions

include Files

Using assert()

Making Items Constant with const

Next Steps in Your C++ Development

Where to Get Help and Advice

Related C++ Topics: Managed C++, C#, and Microsoft's .NET

Staying in Touch






Week 3 In Review

A. Working with Numbers: Binary and Hexadecimal.

Using Other Bases

Converting to Different Bases


Why Base 2?

Bits, Bytes, and Nybbles

What's a KB?

Binary Numbers


B. C++ Keywords.

C. Operator Precedence.

D. Answers.

Day 1



Day 2



Day 3



Day 4



Day 5



Day 6



Day 7



Day 8



Day 9



Day 10



Day 11



Day 12



Day 13



Day 14



Day 15



Day 16



Day 17



Day 18



Day 19



Day 20



Day 21



E. A Look at Linked Lists.

The Component Parts of Your Linked List


Customer Reviews

Most Helpful Customer Reviews

See All Customer Reviews

Sams Teach Yourself C++ in 21 Days 4.4 out of 5 based on 0 ratings. 14 reviews.
Guest More than 1 year ago
I got the book and really enjoyed it . . . at first. Then, about Day 9, I started to get lost. I gave it up for a while, then came back and am working with it and understanding more. Yes, It'll probably take more than 21 days, but not even close to 210 or 2100! Most of my problems, in fact, are due to problems I've had with my compiler!
Guest More than 1 year ago
Very informative. Jesse Liberty makes sure that you understand every important detail before you move on to the next stuff. The codes in this book only comply with the new compilers. So if you have an outdated compiler, then just go get an old C++ book.
Guest More than 1 year ago
This is a wonderful book whether you are beginning or are advanced. If you have no idea of how to program in C++ or if you are in search of a great refernece book, this is what you need! Though I made the mistake of learning C++ as my very first programming language at the age of 15, I was still able to quickly and easily grasp the material. I would recommend this text to absolutely anyone wishing to learn or further their knowledge of this powerful programming language.
Guest More than 1 year ago
I used this book and did well for the 1st 8 chapters. After this point in the book I was mostly lost as I tried to wade through what the author was trying to explain. I ended up taking a C++ class at a local community college which made it much easier for me to continue with the book.
Guest More than 1 year ago
I make no bones about it: if you want to learn a programming language such as C++ you must be very dedicated and serious about doing so. As much as ANY book claims otherwise, this is not a simple task. However, Jesse Liberty's Teach Yourself C++ in 21 Days comes closest to making this long journey a great deal shorter and easier to understand. In programming, obviously, knowledge is power. Mr. Liberty takes no shortcuts in outlining the foundation of an excellent C++ programmer. There is a point where too much knowledge can overwhelm, and this book rarely, if ever, does this. Learning a computer language can be overwhelming in itself; a book such as this is supposed to provide clarity. Teach Yourself succeeds with flying colors covering mandatory basics such as operator overloading, templates, and polymorphism. All of this with colorful analogies that make programming an easier to understand experience. How a few reviewers came up with a one star rating for this book is baffling. I feel those persons to be looking for some kind of miracle to turn them into instant C++ authorities. I hope they can read this next paragraph and learn a few things. Is programming difficult? Yes. There is not another book that will make it any easier. This book is like a college course rolled up in 21 long chapters. I'm not talking about a college course you sit there and just try and pay attention to, I'm saying to take notes, participate, and re-read the material if you need to. This book has been a total inspiration and it's been with me through the thick and thin of the pages of code only to come out shining. Do NOT pass this up.
Guest More than 1 year ago
Jesse Liberty has masterfully crafted this book to introduce ANYONE to C++. Believe me, if I can learn this stuff, you can too! But without Mr. Liberty's unique approach I doubt I would have been able to crack the baseline of knowlege requisite for further study. In short it has given me confidence in my ability to attain knowlege I was never sure I could. GET THIS BOOK!!!
Guest More than 1 year ago
If your new to the world of programing or have past experience THIS IS A BOOK FOR YOU! Very helpfull in almost every way. Dot expect to fully uderstand C in 21 days though... 21 days should give you AT LEAST the basics. Book is also good if read more tha once. Infact i would recomend it... I also recomend useing the same compiler as the book uses...
Guest More than 1 year ago
I had made a couple of attempts at C (not ++) in the past, and became hopelessly befuddled each time. With this very fine book (C++ in 21...about the size of the NYC Telephone directory!) I was able to comprehend much more than I had given myself credit for. It's lucidly witty and (at times) refreshingly humorous approach makes this dauntng task enjoyable. I even finished it in 25 days (close counts for horseshoes, hand grenades and C++ in my book!)! I thank Mr. Liberty and I feel anyone with the determination CAN and WILL finish this book.
Guest More than 1 year ago
Be sure you have the same compiler that this tutorial uses! I wasted a lot of time because I had the wrong version. However as for the book itself; like many computer books it does a really good job of teaching the basic stuff, but after a while it starts getting really tough. I found the examples uninteresting but there is a lot of personal bias there.
Guest More than 1 year ago
This is a great book for newbies, i strongly disagree with those who say this book is for only people who have past programming skills, I am currently reading the book, and They get VERY in depth, and explain everything really well, They have quizzes at the end of every day, to see what you've learned, and they are fairly easy if you have read all up to that point, I suggest this book to EVERYONE.
Guest More than 1 year ago
Uses an easy to read, learn-by-example technique. Great for starting out learning the programming language of choice. Liberty does a great job making sure that you understand the material, by including Notes, syntax examples, DOs and DON'Ts, FAQ boxes, and Cautions, thereby making learning easy, and intuitive.
Guest More than 1 year ago
I learned a great deal about C++ and programming, and I also enjoyed it (wow)! I am greatly indebted to Mr. Liberty. However, it could be confusing if you are not mindful of the errors in the text and source code, most of which are emended on the errata page of the book's website. With that, the book is as close to perfection as a book could be!
Guest More than 1 year ago
While some people have reviewed the book saying it was confusing, I strongly disagree. This book is very in depth. It teaches, and quite well might I add, the basics of C++. After the first few chapters Jesse Liberty excellently covers many more advanced topics of the C++ language. After reading this book, I have found it hard to find other books that cover areas of the language not covered in it. For those people who actually want to learn to program, not those of you who are just trying to learn the basics so you can throw something together for your job or some other reason, this is a great book. I highly recomend it.
Guest More than 1 year ago
I purchased this book with the software package for a higher price(software was 3 different compilers). After I spent three days trying to get thru a one day lesson I decided to return it and buy a different C++ book. This book mentioned that you may recieve errors while you write the programs as instructed,but they do not explain how to correct these errors and email response is slow.