C++ FAQs / Edition 2

Paperback (Print)
Used and New from Other Sellers
Used and New from Other Sellers
from $14.55
Usually ships in 1-2 business days
(Save 79%)
Other sellers (Paperback)
  • All (14) from $14.55   
  • New (7) from $40.72   
  • Used (7) from $14.55   

Overview

In a concise and direct question-and-answer format, C++ FAQs, Second Edition brings you the most efficient solutions to more than four hundred of the practical programming challenges you face every day.

Moderators of the on-line C++ FAQ at comp.lang.c++, Marshall Cline, Greg Lomow, and Mike Girou are familiar with C++ programmers' most pressing concerns. In this book, the authors concentrate on those issues most critical to the professional programmer's work, and they present more explanatory material and examples than is possible on-line. This book focuses on the effective use of C++, helping programmers avoid combining seemingly legal C++ constructs in incompatible ways.

This second edition is completely up-to-date with the final ANSI/ISO C++ Standard. It covers some of the smaller syntax changes, such as "mutable"; more significant changes, such as RTTI and namespaces; and such major innovations as the C++ Standard Library, including the STL. In addition, this book discusses technologies such as Java, CORBA, COM/COM+, and ActiveX--and the relationship all of these have with C++. These new features and technologies are iconed to help you quickly find what is new and different in this edition.

Each question-and-answer section contains an overview of the problem and solution, fuller explanations of concepts, directions for proper use of language features, guidelines for best practices and practices to avoid, and plenty of working, stand-alone examples. This edition is thoroughly cross-referenced and indexed for quick access.

Get a value-added service! Try out all the examples from this book at www.codesaw.com. CodeSaw is a free online learning tool that allows you to experiment with live code from your book right in your browser.

0201309831B11102003

Read More Show Less

Editorial Reviews

Booknews
The moderators of the on-line C++ FAQ at comp.lang.c++ collect and answer the questions most often asked by professional programmers, focusing on the effective use of the programming language and avoiding combining seemingly legal constructs in incompatible ways. No date is noted for the first edition; the second takes account of the final ANSI/ISO standard, major syntax changes and some of the smaller ones, and recent innovations. The explanations are fuller than they are able to provide on line. Annotation c. by Book News, Inc., Portland, Or.
Read More Show Less

Product Details

  • ISBN-13: 9780201309836
  • Publisher: Addison-Wesley
  • Publication date: 12/4/1998
  • Edition description: REV
  • Edition number: 2
  • Pages: 624
  • Sales rank: 1,383,277
  • Product dimensions: 7.25 (w) x 9.18 (h) x 1.28 (d)

Meet the Author

Marshall Cline is President of MT Systems Company, which develops object-oriented systems for large corporations. He has taught object-oriented programming design and analysis to thousands of professionals in both industrial and academic settings. He is the keeper of the official C++ FAQ for the Internet forum comp.lang.c++. He received the PhD in Electrical and Computer Engineering from Clarkson University.

Greg Lomow is a senior architect and developer with fifteen years of experience building applications and distributed systems for the banking and financial services industry as well as mentoring development teams on the effective use of object-oriented technology. He received the PhD in Computer Science from the University of Calgary.

Mike Girou, Chairman of MT Systems Company, has served on national and international C++ standards committees and has twelve years of C++ experience. He received the PhD in Mathematics from the University of Missouri at Columbia.

0201309831AB04062001

Read More Show Less

Read an Excerpt

Introduction

What is the purpose of this chapter?

To explain what the book is all about, how it is related to the electronic FAQ and the first edition, and what conventions are used. This chapter discusses the purpose of the book and the conventions it follows. This chapter also discusses our approach to FAQs and why you should buy this book if you have the first edition or have access to the electronic FAQ.

What are C++ FAQs?

Frequently Asked Questions that should be asked about object-oriented programming and C++.

Each FAQ provides specific guidance in the form of in-depth answers. Many FAQs also provide a complete, working program that illustrates the principles espoused by the FAQ. The word FAQs is pronounced like "facts."

These FAQs aren't necessarily questions people have asked; rather, they are the questions people should ask. Although we never say it publicly, most of these FAQs are based on dumb things we see people do on a fairly regular basis. We got tired of explaining the same fundamental notions over and over again and decided to write them down in this book.

On the other hand, you have taken a step toward OO and C++ competence by purchasing this guidebook; now take the next step by reading and understanding its message.

Who is the target audience for this book?

Professional software developers.

This book is aimed at developers including programmers, architects, and designers. It is a fine way for the experienced programmer to learn object-oriented C++. This book is not for beginners who are just learning to program since it assumes previous programming background. Familiarity with C wouldn't hurt but is not absolutely necessary.

Is this a bookabout C++ per se?

This is a C++ book with a twist.

This book focuses on the object-oriented aspects of C++. Thus, whenever you see the word "C++," you should assume that the words "object-oriented" are present (and we'll occasionally inject the words "object-oriented" as a reminder to the reader).

This book focuses on practical ways to use C++; it does not explore all of the dark corners of the language beloved by "language lawyers." In this way, this book is not the traditional C++ book written from the perspective of the language and stressing the syntax and features of C++ in all their gory detail. Instead, this book concentrates on the key aspects of C++ (such as its OO features) and how to apply them effectively. Another reason for this approach is that the language is so large that it is hard for developers to understand what is relevant and how to apply it.

In this vein, one of the main contributions of this book is to focus on the moral use of C++ rather than simply describing the legal use of C++. In this context, using C++ morally means adhering to a programming discipline (i.e., a subset of all possible combinations of all the constructs of C++) that is relatively risk-free (whereas using C++ legally simply refers to any use of the language that the compiler accepts). We have found that many of the problems that developers run into stem from trying to combine C++ features in incompatible and seemingly random ways; therefore using C++ morally is vital to using C++ effectively.

This book also tries to bridge the gap between software architecture and OO design and C++ programming (see Chapter 4).

Why do developers need a guidebook for C++ and OO technology?

Learning to use C++ and OO properly is a long journey with many pitfalls. Because of the sophistication and complexity of C++, developers need a road map that shows how to use the language properly. For example, inheritance is a powerful facility that can improve the clarity and extensibility of software, but it can also be abused in ways that result in expensive design errors.

The field of object-oriented technology is large, evolving, and heterogeneous. Under these circumstances, a guidebook is essential. These FAQs cover the latest innovations so that you don't have to stumble around for years learning the same lessons others have already learned. The FAQs also expose incorrect and questionable practices.

To be effective, programmers need to understand the language features and how the features of the language can be combined. For example, pointer arithmetic and the is-a conversion (see FAQ 2.24) are both useful, but combining them has some subtle edge effects that can cause big problems; see FAQ 8.16. Similar comments apply when combining overloading and overriding (FAQ 29.02), overriding and default parameters, abstract base classes and assignment (FAQ 24.05), and so on. So it is not enough to understand each feature of C++.

What kind of guidance is given in the answers to these FAQs?

Explanations of language features, directions for using these features properly, and guidelines indicating programming practices to avoid.

The FAQs can be divided into roughly three categories:

FAQs that explain what a particular language feature is and how to use it in compliance with C++ semantics.

FAQs that explain how to use C++ properly. Some of these answers deal with only a single language feature, while others explain how to use several different language features in concert. Combining language features allows sophisticated designs that can simultaneously satisfy multiple technical requirements and business goals.

FAQs that expose poor programming practices. These show design and programming practices that are legal in C++ but should be avoided because they can lead to programs that are bug-ridden, hard to comprehend, expensive to maintain, difficult to extend, and lacking reuse value.

What is the electronic FAQ and why buy this book when the electronic FAQ is free?

The electronic FAQ is a set of C++ questions and answers, originally prepared and distributed on the Internet by Marshall Cline. The Internet version is currently updated and distributed by Marshall and is available through the news group comp.lang.c++. This book has substantially more material than the electronic FAQ.

This book and the electronic FAQ were inspired by a seemingly unquenchable thirst among C++ developers for more and better information about C++ through comp.lang.c++. Addison-Wesley decided to provide an expanded form of that information in book format.

This book covers a broader range of topics and goes into greater depth than the electronic FAQ. It provides deeper coverage of the key points with extensive new examples.

Most of the programming examples are working, stand-alone programs, complete with their own main(), all necessary #include files, and so on. All examples have been compiled directly from the source text of the book; those that are complete programs have also been run.

Why should you buy this edition if you already have a copy of the first edition?

Because the world has changed and you want to keep up with technology. The OO world and the C++ language have changed significantly in the last few years. There are new language constructs such as Run Time Type Identification (RTTI) and namespaces. The Standard Template Library (STL) is a massive addition to the C++ body of essential knowledge. Design notation has apparently standardized on the Unified Modeling Language (UML). Java, CORBA, and ActiveX are now topics that every C++ developer needs to understand. The goal of this second edition is to bring you up to speed on all of these new developments while still keeping the pithy style and FAQ format that was so well received in the first edition.

Finally, the second edition is much more self-contained than the first, with lots of syntax and semantics. We've appreciated all your comments and suggestions and have tried to accommodate them wherever possible.

What conventions are used in this book?

The undecorated word inheritance means "public inheritance." Private or protected inheritance is referred to explicitly.

Similarly the undecorated term derived class means "public derived class." Derived classes produced via private or protected inheritance are explicitly designated "private derived class" or "protected derived class," respectively.

The class names Base and Derived are used as hypothetical class names to illustrate the general relationship between a base class and one of its (publicly) derived classes.

The term out-lined function indicates a function that is called via a normal CALL instruction. In contrast, when an inlined function is invoked, the compiler inserts the object code for that function at the point-of-call.

The term remote ownership is used when an object contains a pointer to another object that the first object is responsible for deleting. The default destruction and copy semantics for objects that contain remote ownership are incorrect, so explicit controls are needed.

To allow compilation while simplifying the presentation to the reader, examples that use the standard library have a line that says using namespace std;. This dumping of the entire standard namespace is acceptable as a short-term conversion technique or as a pedagogical aid, but its use in production systems is controversial. Most authorities recommend introducing class names as needed or using the std:: qualifier.

The term OO is used as an abbreviation for "object-oriented."

The term method is used as a synonym for "member function."

NULL is used rather than 0 to make the code more readable. Organizational standards and guidelines should be consulted before the reader continues this practice.

The term C programming language refers to the ISO version of C.

The compiler is assumed (per the C++ Standard) to insert an implicit return 0; at the end of main().

The intrinsic data type bool is used, which has literal values true and false. For compilers that don't have a built-in bool type, insert the following at the beginning of each example:

typedef char bool; const bool false = 0; const bool true = 1;

The expression new MyClass, where MyClass is some type, is assumed to throw an exception if it runs out of memory-it never returns NULL. Most compilers implement this correctly, but some do not.

Most examples use protected: data rather than private: data. In the real world, this is appropriate for most developers and most applications, but framework developers probably should not use protected: data, since this would create a data coupling between the derived classes and the protected: data of the base class. In general, framework developers should use private: data with protected: access functions.

Type names (names of classes, structs, unions, enums, and typedefs) start with a capital letter; preprocessor symbols are all capitals; all other identifiers start with a lowercase letter. Data member names and class-scoped enumerations end with a single underscore.

It is assumed that the file extensions .cpp and .hpp are appropriate. Some compilers use a different convention.

Universal Modeling Language (UML) notation is used to express design relationships.

The following priorities were used in designing the examples: (1) unity of purpose, (2) compactness, and (3) self-contained functionality. In other words, each example demonstrates one basic point or technique, is as short as possible, and, if possible, is a complete, working program. The examples are not intended for plug-in reuse in industrial-strength settings because balancing the resultant (subtle) tradeoffs would conflict with these priorities.

To avoid complicating the discussions with finding the optimal balance between the use of virtual and inline for member functions, virtual is used more often than strictly necessary (see FAQ 21.15). To achieve compactness, some member functions are defined in the class body even if they wouldn't normally be inline or even if moving them down to the bottom of a header file would improve specification (see FAQ 6.05). Uncalled functions are often left undefined. Some functions that are called are also undefined, since compactness is a higher priority than self-contained functionality. Also for compactness, examples are not wrapped in preprocessor symbols that prevent multiple expansions (see FAQ 2.16).

The examples put the public: part at the beginning of the class rather than at the end of the class. This makes it easier for those who simply want to use the class as opposed to those who want to go in and change the internal implementation of the class. This is normally the right tradeoff since a class is normally used a lot more often than it is changed.

It is assumed that the C++ compiler and standard library are both compliant with the Standard and work correctly. In the real world, this is probably not a safe assumption, and you should be cautious.

Author Biography:

Marshall Cline is President of MT Systems Company, which develops object-oriented systems for large corporations. He has taught object-oriented programming design and analysis to thousands of professionals in both industrial and academic settings. He is the keeper of the official C++ FAQ for the Internet forum comp.lang.c++. He received the PhD in Electrical and Computer Engineering from Clarkson University.

Greg Lomow is a senior architect and developer with fifteen years of experience building applications and distributed systems for the banking and financial services industry as well as mentoring development teams on the effective use of object-oriented technology. He received the PhD in Computer Science from the University of Calgary.

Mike Girou, Chairman of MT Systems Company, has served on national and international C++ standards committees and has twelv C++ experience. He received the PhD in Mathematics from the University of Missouri at Columbia.

Read More Show Less

Table of Contents

Acknowledgments.

I. PRELIMINARIES.

1. Introduction.

What Is the Purpose of This Chapter?

What Are C++ FAQs?

Who Is the Target Audience for This Book?

Is This a Book about C++ Per Se?

Why Do Developers Need a Guidebook for C++ and OO Technology?

What Kind of Guidance Is Given in the Answers to These FAQs?

What Is the Electronic FAQ and Why Buy This Book When the Electronic FAQ Is Free?

Why Should You Buy This Edition if You Already Have a Copy of the First Edition?

What Conventions Are Used in This Book?

2. Basic C++ Syntax and Semantics.

What Is the Purpose of This Chapter?

What Are the Basics of Main()?

What Are the Basics of Functions?

What Are the Basics of Default Parameters?

What Are the Basics of Local (Auto) Objects?

What Are the Basics of Constructing Objects Using Explicit Parameters?

What Are the Basics of Dynamically Allocated (New) Objects?

What Are the Basics of Local Objects within Inner Scopes?

What Are the Basics of Passing Objects by Reference?

What Are the Basics of Passing Objects by Value?

What Are the Basics of Passing Objects by Pointer?

What Are the Basics of Stream Output?

What Are the Basics of Stream Input?

What Are the Basics of Using Classes That Contain Overloaded Operators?

What Are the Basics of Using Container Classes?

What Are the Basics of Creating Class Header Files?

What Are the Basics of Defining a Class?

What Are the Basics of Defining Member Functions?

What Are the Basics of Adding aConstructor to a Class?

What Are the Basics of Adding a Destructor to a Class?

What Are the Basics of Defining a Class That Contains a Pointer to an Object Allocated from the Heap?

What Are the Basics of Global Objects?

What Are the Basics of Throwing and Catching Exceptions?

What Are the Basics of Inheritance and Dynamic Binding?

3. Understanding the Management Perspective.

What Is the Purpose of This Chapter?

What Is the Core Message of This Chapter (and This Book)?

Why Are the Managers in Charge Rather Than the Developers Who Understand Technology?

How Can Someone Manage Something They Don't Understand?

What Is the Most Common Mistake on C++ and OO Projects?

What's the “Software Peter Principle?”

Should an Organization Use OO on All Its Projects?

Can OO Be Ignored Until It Goes Away?

What OO Language Is Best?

What Is the Right Approach to Processes and Tools?

What Is the Right Approach with Off-the-Shelf Class Libraries and Frameworks?

4. The Architectural Perspective.

What Is the Purpose of This Chapter?

Why Is Software Architecture Important?

What Should the Architecture Be Based on, the Problem Being Solved or the Problem Domain?

Should the Software Architecture Be Based on the Policy of the Problem?

Do Customers Ever Change Their Requirements?

Are Stable Requirements Desirable?

What Is the Key to Planning for Change?

What Is a Framework?

What Is the “Inversion of Control” Exhibited by Frameworks?

What Is an Extensible, Domain-Specific Framework?

What Characteristics Make a Framework Extensible Yet Domain-Specific?

What Happens if the Domain Analysis Is Incorrect?

How Much Effort Should Be Expended to Support Change — That Is, How Much Is Extensibility Worth?

How Does an Architect Make the Software Architecture Flexible?

What Is the Secret to Achieving Reuse?

II. OBJECT-ORIENTED DESIGN.

5. Object-Oriented Fundamentals.

What Is the Purpose of This Chapter?

Why Is the World Adopting OO Technology?

What Are Some of the Benefits of Using C++ for OO Programming?

What Are the Fundamental Concepts of Object-Oriented Technology?

Why Are Classes Important?

What Is an Object?

What Are the Desirable Qualities of an Object?

How Are Classes Better Than the Three Basic Building Blocks of Procedural Software?

What Is the Purpose of Composition?

What Is the Purpose of Inheritance?

What Are the Advantages of Polymorphism and Dynamic Binding?

How Does OO Help Produce Flexible and Extensible Software?

How Can Old Code Call New Code?

What Is an Abstraction and Why Is It Important?

Should Abstractions Be User-Centric or Developer-Centric?

What's the Difference between Encapsulation and Abstraction?

What Are the Consequences of Encapsulating a Bad Abstraction?

What's the Value of Separating Interface from Implementation?

How Can Separating Interface from Implementation Improve Performance as Well as Flexibility?

What Is the Best Way to Create a Good Interface to an Abstraction?

How Are Get/Set Member Functions Related to Poorly Designed Interfaces?

Should There Be a Get and a Set Member Function for Each Member Datum?

Is the Real Purpose of a Class to Export Data?

Should OO Be Viewed as Data-Centric?

6. Specification of Observable Behavior.

What Is the Purpose of This Chapter?

Should Users of a Member Function Rely on What the Code Actually Does or on the Specification?

What Are the Advantages of Relying on the Specification Rather Than the Implementation?

What Are Advertised Requirements and Advertised Promises?

How Are the Advertised Requirements and Advertised Promises of the Member Functions Specified?

Why Are Changes Feared in Development Organizations That Don't Use Specification?

How Do Developers Determine if a Proposed Change Will Break Existing Code?

What Are the Properties of a Substitutable (Backward Compatible) Change in a Specification?

How Can It Be Shown That the Implementation of a Member Function Fulfills Its Specification?

Is It Possible to Keep the Specification Synchronized with the Code?

7. Proper Inheritance.

What Is Proper Inheritance?

What Are the Benefits of Proper Inheritance?

What Is Improper Inheritance?

Isn't the Difference between Proper and Improper Inheritance Obvious?

Is Substitutability Based on What the Code Does or What the Specification Promises the Code Will Do?

Is It Proper to Revoke (Hide) an Inherited Public: Member Function?

What Is Specialization?

What Do Subsets Have to Do with Proper Inheritance?

8. Detecting and Correcting Improper Inheritance.

Can Improper Inheritance Wreck a Project?

What's the Best Way to Learn How to Avoid Improper Inheritance?

Is Intuition a Reliable Guide to Understanding Proper Inheritance?

Is an Ostrich a Kind-Of Bird?

Should an Overridden Virtual Function Throw an Exception?

Can an Overridden Virtual Function Be a No-Op?

Why Does C++ Make It So Hard to Fix the Ostrich/Bird Dilemma?

Should Circle Inherit from Ellipse?

What Can Be Done about the Asymmetric-Circle Dilemma?

What Is the One Issue in These FAQs That Doesn't Seem to Die?

Should Stack Inherit from List?

Is Code Reuse the Main Purpose of Inheritance?

Is Container-of-Thing a Kind-Of Container-of-Anything?

Is Bag-of-Apple a Kind-Of Bag-of-Fruit, Assuming Bag-of-Fruit Allows the Insertion of Any Kind-Of Fruit?

Is Parking-Lot-for-Cars a Kind-Of Parking-Lot-for-Arbitrary-Vehicles (Assuming Parking-Lot-for-Vehicles Allows Parking Any Kind-Of Vehicle)?

Is Array-Of Derived a Kind-Of Array-Of Base?

Does the Fact That an Array-Of Derived Can Be Passed as an Array-Of Base Mean That Arrays Are Bad?

9. Error Handling Strategies.

Is Error Handling a Major Source of Fundamental Mistakes?

How Should Runtime Errors Be Handled in C++?

What Happens to Objects in Stack Frames That Become Unwound During the Throw / Catch Process?

What Is an Exception Specification?

What Are the Disadvantages of Using Return Codes for Error Handling?

What Are the Advantages of Throw...Catch?

Why Is It Helpful to Separate Normal Logic from Exception Handling Logic?

What Is the Hardest Part of Using Exception Handling?

When Should a Function Throw an Exception?

What Is the Best Approach for the Hierarchy of Exception Objects?

How Should Exception Classes Be Named?

Where Do Setjmp and Longjmp Belong in C++?

10. Testing Strategies.

What Is the Purpose of This Chapter?

What Are the Advantages of Self-Testing Objects?

What Are Some Common Excuses People Use for Not Building Self-Testing Into Their Objects?

What Will Happen if Techniques Like Those Presented Here Are Not Used?

When Is a Class Correct?

What Is Behavioral Self-Testing?

What Is a Class Invariant?

Why Should the Invariant Be Captured Explicitly?

When Should the Testinvariant() Member Function Be Called?

What Can Be Done to Ensure That an Object Doesn't Get Blown Away by a Wild Pointer?

III. LANGUAGE FACILITIES.

11. References.

What Is a Reference?

What Does “Referent” Mean?

When Can a Reference Be Attached to Its Referent?

What Happens When a Value Is Assigned to a Reference?

What Is a Local Reference?

What Does It Mean to Return a Reference?

What Is the Result of Taking the Address of a Reference?

Can a Reference Be Made to Refer to a Different Referent?

Why Use References When Pointers Can Do Everything References Can Do?

Aren't References Just Pointers in Disguise?

When Are Pointers Needed?

Why Do Some People Hate References?

Does Int& Const X Make Sense?

12. New and Delete.

Does New Do More Than Allocate Memory?

Why Is New Better Than Good Old Trustworthy Malloc()?

Does C++ Have a Counterpart to Realloc() That Goes Along with New and Delete?

Can Pointers Returned from New Be Deallocated with Free()? Can Pointers Returned from Malloc() Be Deallocated with Delete?

Does Delete P Delete the Pointer P or the Referent *P?

Should the Pointer Returned from New Fred() Be Checked to See if It Is NULL?

How Can New Be Convinced to Return NULL Rather Than Throw an Exception?

How Can New Be Set Up to Automatically Flush Pools of Recycled Objects Whenever Memory Runs Low?

What Happens if Delete P Is Called When P Is NULL?

What Happens When a Pointer Is Deleted Twice?

How Can an Array of Things Be Allocated and Deallocated?

What if Delete P (Not Delete[] P) Is Used to Delete an Array Allocated Via New Fred[N]?

Can the [] of Delete[] P Be Dropped When P Points to an Array of Some Built-in Type Such as Char?

How Is an Object Constructed at a Predetermined Position in Memory?

How Can Class Fred Guarantee That Fred Objects Are Created Only with New and Not on the Stack?

How Are Objects Created by Placement New Destroyed?

in P = New Fred(), Does the Fred Memory “Leak” if the Fred Constructor Throws an Exception?

Is It Legal (and Moral) for a Member Function to Say Delete This?

After P = New Fred[N], How Does the Compiler Know That There Are N Objects to Be Destructed During Delete[] P?

13. Inline Functions.

What Is the Purpose of Inline Functions?

What Is the Connection between the Keyword “Inline” and “Inlined” Functions?

Are There Any Special Rules about Inlining?

What Is the One-Definition Rule (ODR)?

What Are Some Performance Considerations with Inline Functions?

Do Inlined Functions Improve Performance?

Do Inlined Functions Increase the Size of the Executable Code?

Why Shouldn't the Inlining Decision Be Made When the Code Is First Written?

What Happens When a Programmer Uses an Inlined Function Obtained from a Third Party?

Is There an Easy Way to Swap between Inline and Non-Inline Code?

14. Const Correctness.

How Should Pointer Declarations Be Read?

How Can C++ Programmers Avoid Making Unexpected Changes to Objects?

Does Const Imply Runtime Overhead?

Does Const Allow the Compiler to Generate More Efficient Code?

Is Const Correctness Tedious?

Why Should Const Correctness Be Done Sooner Rather Than Later?

What's the Difference between an Inspector and a Mutator?

When Should a Member Function Be Declared as Const?

Does Const Apply to the Object's Bitwise State or Its Abstract State?

When Should Const Not Be Used in Declaring Formal Parameters?

When Should Const Not Be Used in Declaring a Function Return Type?

How Can a “Nonobservable” Data Member Be Updated within a Const Member Function?

Can an Object Legally Be Changed Even Though There Is a Const Reference (Pointer) to It?

Does Const_Cast Mean Lost Optimization Opportunities?

15. Namespaces.

What Is the Purpose of This Chapter?

What Is a Namespace?

How Can Code Outside a Namespace Use Names Declared within That Namespace?

What Happens if Two Namespaces Contain the Same Name?

What Are Some of the Rules for Using Namespaces?

What Is Name Lookup?

What Are the Tradeoffs between the Various Techniques for Using Names from a Namespace, Particularly the Standard Namespace?

Can Namespaces Break Code?

Do Namespaces Have Any Other Applications?

How Do Namespaces Solve the Problem of Long Identifiers?

16. Using Static.

What Is the Purpose of This Chapter?

What Are Static Class Members?

What Is an Analogy for Static Data Members?

Can Inline Functions Safely Access Static Data Members?

What Is an Analogy for Static Member Functions?

How Is a Static Data Member Similar to a Global Variable?

How Is a Static Member Function Similar to a Friend Function?

What Is the Named Constructor Idiom?

How Should Static Member Functions Be Called?

Why Might a Class with Static Data Members Get Linker Errors?

How Is a Const Static Data Member Initialized?

What Is the Right Strategy for Implementing a Function That Needs to Maintain State between Calls?

How Can the Function Call Operator Help with Functionoids?

Is It Safe to Be Ignorant of the Static Initialization Order Problem?

What Is a Simple and Robust Solution to the Static Initialization Order Problem?

What if the Static Object's Destructor Has Important Side Effects That Must Eventually Occur?

What if the Static Object's Destructor Has Important Side Effects That Must Eventually Occur and the Static Object Must Be Accessed by Another Static Object's Destructor?

What Are Some Criteria for Choosing between All These Various Techniques?

17. Derived Classes.

What Is the Purpose of This Chapter?

How Does C++ Express Inheritance?

What Is a Concrete Derived Class?

Why Can't a Derived Class Access the Private: Members of Its Base Class?

How Can a Base Class Protect Derived Classes So That Changes to the Base Class Will Not Affect Them?

Can a Derived Class Pointer Be Converted Into a Pointer to Its Public Base Class?

How Can a Class Y Be a Kind-Of Another Class X as Well as Getting the Bits of X?

How Can a Class Y Get the Bits of an Existing Class X Without Making Y a Kind-Of X?

How Can a Class Y Be a Kind-Of Another Class X Without Inheriting the Bits of X?

18. Access Control.

What Is the Purpose of This Chapter?

How Are Private:, Protected:, and Public: Different?

Why Can't Subclasses Access the Private: Parts of Their Base Class?

What's the Difference between the Keywords Struct and Class?

When Should a Data Member Be Protected: Rather Than Private:?

Why Is Private: the Default Access Level for a Class?

19. Friend Classes and Friend Functions.

What Is a Friend?

What's a Good Mental Model for Friend Classes?

What Are Some Advantages of Using Friend Classes?

Do Friends Violate the Encapsulation Barrier?

What Is a Friend Function?

When Should a Function Be Implemented as a Friend Function Rather Than a Member Function?

What Are Some Guidelines to Make Sure Friend Functions Are Used Properly?

What Does It Mean That Friendship Isn't Transitive?

What Does It Mean That Friendship Isn't Inherited?

What Does It Mean That Friends Aren't Virtual?

What Qualities Suggest a Friend Function Rather Than a Member Function?

Should Friend Functions Be Declared in the Private:, Protected:, or Public: Section of a Class?

What Is a Private Class?

How Are Objects of a Class Printed?

How Do Objects of a Class Receive Stream Input?

20. Constructors and Destructors.

What Is the Purpose of a Constructor?

What Is C++'S Constructor Discipline?

What Is the Purpose of a Destructor?

What Is C++'S Destructor Discipline?

What Happens When a Destructor Is Executed?

What Is the Purpose of a Copy Constructor?

When Is a Copy Constructor Invoked?

What Is the “Default Constructor?”

Should One Constructor Call Another Constructor as a Primitive?

Does the Destructor for a Derived Class Need to Explicitly Call the Destructor of Its Base Class?

How Can a Local Object Be Destructed Before the End of Its Function?

What Is a Good Way to Provide Intuitive, Multiple Constructors for a Class?

When the Constructor of a Base Class Calls a Virtual Function, Why Isn't the Override Called?

When a Base Class Destructor Calls a Virtual Function, Why Isn't the Override Called?

What Is the Purpose of Placement New?

21. Virtual Functions.

What Is the Purpose of This Chapter?

What Is a Virtual Member Function?

How Much Does It Cost to Call a Virtual Function Compared to Calling a Normal Function?

How Does C++ Perform Static Typing While Supporting Dynamic Binding?

Can Destructors Be Virtual?

What Is the Purpose of a Virtual Destructor?

What Is a Virtual Constructor?

What Syntax Should Be Used When a Constructor or Destructor Calls a Virtual Function in Its Object?

Should the Scope Operator :: Be Used When Invoking Virtual Member Functions?

What Is a Pure Virtual Member Function?

Can a Pure Virtual Function Be Defined in the Same Class That Declares It?

How Should a Virtual Destructor Be Defined When It Has No Code?

Can an ABC Have a Pure Virtual Destructor?

How Can the Compiler Be Kept from Generating Duplicate Out-Lined Copies of Inline Virtual Functions?

Should a Class with Virtual Functions Have at Least One Non-Inline Virtual Function?

22. Initialization Lists.

What Are Constructor Initialization Lists?

What Will Happen if Constructor Initialization Lists Are Not Used?

What's the Guideline for Using Initialization Lists in Constructor Definitions?

Is It Normal for Constructors to Have Nothing Inside Their Body?

How Is a Const Data Member Initialized?

How Is a Reference Data Member Initialized?

Are Initializers Executed in the Same Order in Which They Appear in the Initialization List?

How Should Initializers Be Ordered in a Constructor's Initialization List?

Is It Moral for One Member Object to Be Initialized Using Another Member Object in the Constructor's Initialization List?

What if One Member Object Has to Be Initialized Using Another Member Object?

Are There Exceptions to the Rule “Initialize All Member Objects in an Initialization List?”

How Can an Array of Objects Be Initialized with Specific Initializers?

23. Operator Overloading.

Are Overloaded Operators Like Normal Functions?

When Should Operator Overloading Be Used?

What Operators Can't Be Overloaded?

Is the Goal of Operator Overloading to Make the Class Easier to Understand?

Why Do Subscript Operators Usually Come in Pairs?

What Is the Most Important Consideration for Operators Such as +=, +, and =?

How Are the Prefix and Postfix Versions of Operator++ Distinguished?

What Should the Prefix and Postfix Versions of Operator++ Return?

How Can a Matrix-Like Class Have a Subscript Operator That Takes More Than One Subscript?

Can a ** Operator Serve as an Exponentiation Operator?

24. Assignment Operators.

What Should Assignment Operators Return?

What Is Wrong with an Object Being Assigned to Itself?

What Should Be Done about Self-Assignment?

Should an Assignment Operator Throw an Exception After Partially Assigning an Object?

How Should the Assignment Operator Be Declared in an ABC?

When Should a User-Defined Assignment Operator Mimic the Assignment Operator That the Compiler Would Generate Automatically?

What Should Be Returned by Private: and Protected: Assignment Operators?

Are There Techniques That Increase the Likelihood That the Compiler-Synthesized Assignment Operator Will Be Right?

How Should the Assignment Operator in a Derived Class Behave?

Can an ABC's Assignment Operator Be Virtual?

What Should a Derived Class Do a Base Class's Assignment Operator Is Virtual?

Should the Assignment Operator Be Implemented by Using Placement New and the Copy Constructor?

25. Templates.

What Is the Purpose of Templates?

What Are the Syntax and Semantics for a Class Template?

How Can a Template Class Be Specialized to Handle Special Cases?

What Are the Syntax and Semantics for a Function Template?

Should a Template Use Memcpy() to Copy Objects of Its Template Argument?

Why Does the Compiler Complain about >≫ When One Template Is Used Inside Another?

26. Exception Tactics.

What Belongs in a Try Block?

When Should a Function Catch an Exception?

Should a Catch Block Fully Recover from an Error?

How Should a Constructor Handle a Failure?

What Are Zombie Objects (and Why Should They Be Avoided)?

What Should an Object Do if One of Its Member Objects Could Throw an Exception During Its Constructor?

Should Destructors Throw Exceptions When They Fail?

Should Destructors Call Routines That May Throw Exceptions?

Should Resource Deallocation Primitives Signal Failure by Throwing an Exception?

What Should the Terminate() Function Do?

What Should the Unexpected() Function Do?

Under What Circumstances Can an Overridden Virtual Member Function Throw Exceptions Other Than Those Listed by the Specification of the Member Function in the Base Class?

How Might the Exception-Handling Mechanism Cause a Program to Silently Crash?

27. Types and RTTI.

What Is the Purpose of This Chapter?

What Is Static Type Checking?

What Is Dynamic Type Checking?

What Is the Basic Problem with Dynamic Type Checking?

How Can Dynamic Type Checking Be Avoided?

Are There Better Alternatives to Dynamic Type Checking?

What Is a Capability Query?

What Is an Alternative to Dynamic Type Checking with Containers?

Are There Cases Where Dynamic Type Checking Is Necessary?

Given a Pointer to an ABC, How Can the Class of the Referent Be Found?

What Is a Downcast?

What Is an Alternative to Using Downcasts?

Why Are Downcasts Dangerous?

Should the Inheritance Graph of C++ Hierarchies Be Tall or Short?

Should the Inheritance Graph of C++ Hierarchies Be Monolithic or a Forest?

What Is Runtime Type Identification (RTTI)?

What Is the Purpose of Dynamic_Cast≪T≫()?

Is Dynamic_Cast≪T≫() a Panacea?

What Does Static_Cast≪T≫() Do?

What Does Typeid() Do?

Are There Any Hidden Costs for Type-Safe Downcasts?

28. Containers.

What Are Container Classes and What Are the Most Common Mistakes Made with Container Classes?

Are Arrays Good or Evil?

Should Application Development Organizations Create Their Own Container Classes?

What Are Some Common Mistakes with Containers of Pointers?

Does This Mean That Containers of Pointers Should Be Avoided?

Surely Good Old-Fashioned Char* Is an Exception, Right?

Can Auto_Ptr≪T≫ Simplify Ownership Problems with Containers of Pointers?

Can a Java-Like Object Class Simplify Containers in C++?

What's the Difference between a Homogeneous and a Heterogeneous Container?

Is It a Good Idea to Use a “Best of Breed” Approach When Selecting Container Classes?

Should All Projects Use C++'S Standardized Containers?

What Are the C++ Standardized Container Classes?

What Are the Best Applications for the Standardized C++ Sequence Container Classes?

What Are the Best Situations for the Standardized C++ Associative Container Classes?

IV. TOPICS.

29. Mixing Overloading with Inheritance.

What Is the Difference between Overloaded Functions and Overridden Functions?

What Is the Hiding Rule?

How Should the Hiding Rule Be Handled?

What Should a Derived Class Do When It Redefines Some but Not All of a Set of Overloaded Member Functions Inherited from the Base Class?

Can Virtual Functions Be Overloaded?

30. The Big Three.

What Is the Purpose of This Chapter?

What Are the Big Three?

What Happens When an Object Is Destroyed That Doesn't Have an Explicit Destructor?

What Happens if an Object Is Copied but Doesn't Have an Explicit Copy Constructor?

What Happens When an Object That Doesn't Have an Explicit Assignment Operator Is Assigned?

What Is the Law of the Big Three?

Which of the Big Three Usually Shows Up First?

What Is Remote Ownership?

How Is Remote Ownership Special?

What if a Class Owns a Referent and Doesn't Have All of the Big Three?

Are There Any C++ Classes That Help Manage Remote Ownership?

Does Auto_Ptr Enforce the Law of the Big Three and Solve the Problems Associated with Remote Ownership?

Are There Cases Where One or Two of the Big Three May Be Needed but Not All Three?

Are There Any Other Circumstances That Might Explicitly Warrant the Big Three?

Why Does Copying an Object Using Memcpy() Cause a Program Crash?

Why Do Programs with Variable-Length Argument Lists Crash?

Why Do Programs That Use Realloc() to Reallocate an Array of Objects Crash?

31. Using Objects to Prevent Memory Leaks.

When Are Memory Leaks Important?

What Is the Easiest Way to Avoid Memory Leaks?

What Are the Most Important Principles for Resource Management?

Should the Object That Manages a Resource Also Perform Operations That May Throw Exceptions?

Should an Object Manage Two or More Resources?

What if an Object Has a Pointer to an Allocation and One of the Object's Member Functions Deletes the Allocation?

How Should a Pointer Variable Be Handled After Being Passed to Delete?

What Should Be Done with a Pointer to an Object That Is Allocated and Deallocated in the Same Scope?

How Easy Is It to Implement Reference Counting with Pointer Semantics?

Is Reference Counting with Copy-on-Write Semantics Hard to Implement?

How Can Reference Counting Be Implemented with Copy-on-Write Semantics for a Hierarchy of Classes?

32. Wild Pointers and Other Devilish Errors.

What Is a Wild Pointer?

What Happens to a Program That Has Even One Wild Pointer?

What Does the Compiler Mean by the Warning “Returning a Reference to a Local Object?”

How Should Pointers Across Block Boundaries Be Controlled?

Is the Reference-Versus-Pointer Issue Influenced by Whether or Not the Object Is Allocated from the Heap?

When Should C-Style Pointer Casts Be Used?

Is It Safe to Bind a Reference Variable to a Temporary Object?

Should a Parameter Passed by Const Reference Be Returned by Const Reference?

Should Template Functions for Things Like Min(X,Y) or Abs(X) Return a Const Reference?

When Is Zero Not Necessarily Zero?

33. High-Performance Software.

Is Bad Performance a Result of Bad Design or Bad Coding?

What Are Some Techniques for Improving Performance?

What Is an Advantage of Using Pointers and References?

What Is a Disadvantage of Lots of References and Pointers?

How Else Can Member Objects Improve Performance Over Pointers?

Which Is Better, ++I or I++?

What Is the Performance Difference between Fred X(5); and Fred Y = 5; and Fred Z = Fred(5);?

What Kinds of Applications Should Consider Using Final Classes and Final Member Functions?

What Is a Final Class?

What Is a Final Member Function?

How Can Final Classes and Final Member Functions Improve Performance?

When Should a Nonfinal Virtual Function Be Invoked with a Fully Qualified Name?

Should Full Qualification Be Used When Calling Another Member Function of the Same Class?

Do Final Classes and Final Member Functions Cause a Lot of Code Duplication?

Why Do Some Developers Dislike Final Member Functions and Final Classes?

Can a Programming Language — Rather Than Just the Compiler — Affect the Performance of Software?

34. COM and Active X.

Who Should Read This Chapter?

What Is the Component Object Model?

What Are Activex and OLE?

What Does the Name Component Object Model Mean?

What Is a “Binary Object Model?”

What Are the Key Features of COM?

What Are Guids?

Why Does COM Need Guids (and Clsids and Iids)?

What Is an Interface?

What Is the Iunknown Interface?

How Many Ways Are There to Specify COM Interfaces?

What Are COM Classes and COM Objects?

How Hard Is It for Callers to Create and Use a COM Object?

How Does COM Provide Language Transparency?

How Does COM Provide Location Transparency?

What Types of Errors Occur Due to Reference Counting?

What Mechanism Does COM Define for Error Handling?

How Are Interfaces Versioned?

Is COM Object Oriented?

What Is the Biggest Problem with COM?

What Are the Major Differences between COM and C++?

When Should a Class Be Defined as a COM Class?

What Is Automation?

What Are Dispatch Interfaces?

When Should a Class Expose a Dispatch Interface?

How Does Automation Work?

How Does Invoke Accomplish All of This?

What Is a Type Library?

What Are the Benefits of Using Type Libraries?

How Do Type Libraries Improve Performance?

What Are Dual Interfaces?

What Limitations Are There on Dual Interfaces?

What Are OLE Custom Controls and Activex Controls?

Why Do Activex Controls Differ from OLE Custom Controls?

What Is a Control Container?

What Are Component Categories?

What Are Events?

What Is DCOM?

How Stable Is DCOM's Infrastructure?

What Is COM+?

35. Transitioning to CORBA.

What Is CORBA?

What Is an ORB?

What Is IDL?

What Is COS?

What Is OMA?

What Is OMG?

What Is the Purpose of This Chapter?

What Is the Most Important Message of This Chapter?

What Are the Important Concepts Behind CORBA?

Isn't OMG IDL Pretty Much the Same as C++?

Is the Lifecycle of a CORBA Object the Same as the Lifecycle of a C++ Object?

Is the C++ Code That Interacts with the CORBA Implementation Portable to a Different CORBA Vendor?

How Do CORBA Exceptions Compare to C++ Exceptions?

Which CORBA Implementation Is Best? Is CORBA Better Than COM?

36. C Language Considerations.

What Are the Main Issues When Mixing C and C++ Code in the Same Application?

How Can C++ Code Call C Code?

How Can C Code Call C++ Code?

Why Is the Linker Giving Errors for C Functions Called from C++ Functions and Vice Versa?

How Can an Object of a C++ Class Be Passed to or from a C Function?

Can a C Function Directly Access Data in an Object of a C++ Class?

Can C++ I/O (≪Iostream≫) Be Mixed with C I/O (≪Stdio.H≫)?

Which Is Safer: ≪Iostream≫ or ≪Stdio.H≫?

Which Is More Extensible: ≪Iostream≫ or ≪Stdio.H≫?

Which Is More Flexible: ≪Iostream≫ or ≪Stdio.H≫?

Why Does It Seem That C++ Programming Feels Farther Away from the Machine Than C?

Why Does C++ Do More Things Behind Your Back Than C Does?

37. Private and Protected Inheritance.

What Are Private Inheritance and Protected Inheritance?

What Is the Difference between Private Inheritance and Protected Inheritance?

What Is the Syntax and Semantics for Private and Protected Inheritance?

When Should Normal Has-a Be Used, Rather Than Private or Protected Inheritance?

What Are the Access Rules for Public, Protected, and Private Inheritance?

In a Private or Protected Derived Class, How Can a Member Function That Was Public in the Base Class Be Made Public in the Derived Class?

Should a Pointer Be Cast from a Private or Protected Derived Class to Its Base Class?

38. Pointers to Member Functions.

What Is the Type of a Pointer to a Nonstatic Member Function?

Can Pointers to Nonstatic Member Functions Be Passed to Signal Handlers, X Event Call-Back Handlers, and So on, That Expect C-Like Function Pointers?

What Is One of the Most Common Errors When Using Pointers to Member Functions?

How Is an Array of Pointers to Nonstatic Member Functions Declared?

39. The Transition to OO and C++.

Who Should Read This Chapter?

What Are the Key Messages of This Chapter?

How Many Stages of Technical Expertise Are There in the Transition?

Why Bother Defining Levels of Expertise?

Can OO/C++ Be Learned from a Book?

Can OO/C++ Be Learned from a Course?

What Is the Key to Learning OO/C++?

Are Small Projects a Good Way to Get Your Feet Wet?

Does Being a Good C Programmer Help When Learning OO/C++?

What Skills Help When Learning OO/C++?

Index. 0201309831T04062001

Read More Show Less

Preface

Introduction

What is the purpose of this chapter?

To explain what the book is all about, how it is related to the electronic FAQ and the first edition, and what conventions are used. This chapter discusses the purpose of the book and the conventions it follows. This chapter also discusses our approach to FAQs and why you should buy this book if you have the first edition or have access to the electronic FAQ.

What are C++ FAQs?

Frequently Asked Questions that should be asked about object-oriented programming and C++.

Each FAQ provides specific guidance in the form of in-depth answers. Many FAQs also provide a complete, working program that illustrates the principles espoused by the FAQ. The word FAQs is pronounced like "facts."

These FAQs aren't necessarily questions people have asked; rather, they are the questions people should ask. Although we never say it publicly, most of these FAQs are based on dumb things we see people do on a fairly regular basis. We got tired of explaining the same fundamental notions over and over again and decided to write them down in this book.

On the other hand, you have taken a step toward OO and C++ competence by purchasing this guidebook; now take the next step by reading and understanding its message.

Who is the target audience for this book?

Professional software developers.

This book is aimed at developers including programmers, architects, and designers. It is a fine way for the experienced programmer to learn object-oriented C++. This book is not for beginners who are just learning to program since it assumes previous programming background. Familiarity with C wouldn't hurt but is not absolutely necessary.

Is this abookabout C++ per se?

This is a C++ book with a twist.

This book focuses on the object-oriented aspects of C++. Thus, whenever you see the word "C++," you should assume that the words "object-oriented" are present (and we'll occasionally inject the words "object-oriented" as a reminder to the reader).

This book focuses on practical ways to use C++; it does not explore all of the dark corners of the language beloved by "language lawyers." In this way, this book is not the traditional C++ book written from the perspective of the language and stressing the syntax and features of C++ in all their gory detail. Instead, this book concentrates on the key aspects of C++ (such as its OO features) and how to apply them effectively. Another reason for this approach is that the language is so large that it is hard for developers to understand what is relevant and how to apply it.

In this vein, one of the main contributions of this book is to focus on the moral use of C++ rather than simply describing the legal use of C++. In this context, using C++ morally means adhering to a programming discipline (i.e., a subset of all possible combinations of all the constructs of C++) that is relatively risk-free (whereas using C++ legally simply refers to any use of the language that the compiler accepts). We have found that many of the problems that developers run into stem from trying to combine C++ features in incompatible and seemingly random ways; therefore using C++ morally is vital to using C++ effectively.

This book also tries to bridge the gap between software architecture and OO design and C++ programming (see Chapter 4).

Why do developers need a guidebook for C++ and OO technology?

Learning to use C++ and OO properly is a long journey with many pitfalls. Because of the sophistication and complexity of C++, developers need a road map that shows how to use the language properly. For example, inheritance is a powerful facility that can improve the clarity and extensibility of software, but it can also be abused in ways that result in expensive design errors.

The field of object-oriented technology is large, evolving, and heterogeneous. Under these circumstances, a guidebook is essential. These FAQs cover the latest innovations so that you don't have to stumble around for years learning the same lessons others have already learned. The FAQs also expose incorrect and questionable practices.

To be effective, programmers need to understand the language features and how the features of the language can be combined. For example, pointer arithmetic and the is-a conversion (see FAQ 2.24) are both useful, but combining them has some subtle edge effects that can cause big problems; see FAQ 8.16. Similar comments apply when combining overloading and overriding (FAQ 29.02), overriding and default parameters, abstract base classes and assignment (FAQ 24.05), and so on. So it is not enough to understand each feature of C++.

What kind of guidance is given in the answers to these FAQs?

Explanations of language features, directions for using these features properly, and guidelines indicating programming practices to avoid.

The FAQs can be divided into roughly three categories:

FAQs that explain what a particular language feature is and how to use it in compliance with C++ semantics.

FAQs that explain how to use C++ properly. Some of these answers deal with only a single language feature, while others explain how to use several different language features in concert. Combining language features allows sophisticated designs that can simultaneously satisfy multiple technical requirements and business goals.

FAQs that expose poor programming practices. These show design and programming practices that are legal in C++ but should be avoided because they can lead to programs that are bug-ridden, hard to comprehend, expensive to maintain, difficult to extend, and lacking reuse value.

What is the electronic FAQ and why buy this book when the electronic FAQ is free?

The electronic FAQ is a set of C++ questions and answers, originally prepared and distributed on the Internet by Marshall Cline. The Internet version is currently updated and distributed by Marshall and is available through the news group comp.lang.c++. This book has substantially more material than the electronic FAQ.

This book and the electronic FAQ were inspired by a seemingly unquenchable thirst among C++ developers for more and better information about C++ through comp.lang.c++. Addison-Wesley decided to provide an expanded form of that information in book format.

This book covers a broader range of topics and goes into greater depth than the electronic FAQ. It provides deeper coverage of the key points with extensive new examples.

Most of the programming examples are working, stand-alone programs, complete with their own main(), all necessary #include files, and so on. All examples have been compiled directly from the source text of the book; those that are complete programs have also been run.

Why should you buy this edition if you already have a copy of the first edition?

Because the world has changed and you want to keep up with technology. The OO world and the C++ language have changed significantly in the last few years. There are new language constructs such as Run Time Type Identification (RTTI) and namespaces. The Standard Template Library (STL) is a massive addition to the C++ body of essential knowledge. Design notation has apparently standardized on the Unified Modeling Language (UML). Java, CORBA, and ActiveX are now topics that every C++ developer needs to understand. The goal of this second edition is to bring you up to speed on all of these new developments while still keeping the pithy style and FAQ format that was so well received in the first edition.

Finally, the second edition is much more self-contained than the first, with lots of syntax and semantics. We've appreciated all your comments and suggestions and have tried to accommodate them wherever possible.

What conventions are used in this book?

The undecorated word inheritance means "public inheritance." Private or protected inheritance is referred to explicitly.

Similarly the undecorated term derived class means "public derived class." Derived classes produced via private or protected inheritance are explicitly designated "private derived class" or "protected derived class," respectively.

The class names Base and Derived are used as hypothetical class names to illustrate the general relationship between a base class and one of its (publicly) derived classes.

The term out-lined function indicates a function that is called via a normal CALL instruction. In contrast, when an inlined function is invoked, the compiler inserts the object code for that function at the point-of-call.

The term remote ownership is used when an object contains a pointer to another object that the first object is responsible for deleting. The default destruction and copy semantics for objects that contain remote ownership are incorrect, so explicit controls are needed.

To allow compilation while simplifying the presentation to the reader, examples that use the standard library have a line that says using namespace std;. This dumping of the entire standard namespace is acceptable as a short-term conversion technique or as a pedagogical aid, but its use in production systems is controversial. Most authorities recommend introducing class names as needed or using the std:: qualifier.

The term OO is used as an abbreviation for "object-oriented."

The term method is used as a synonym for "member function."

NULL is used rather than 0 to make the code more readable. Organizational standards and guidelines should be consulted before the reader continues this practice.

The term C programming language refers to the ISO version of C.

The compiler is assumed (per the C++ Standard) to insert an implicit return 0; at the end of main().

The intrinsic data type bool is used, which has literal values true and false. For compilers that don't have a built-in bool type, insert the following at the beginning of each example:

typedef char bool; const bool false = 0; const bool true = 1;

The expression new MyClass, where MyClass is some type, is assumed to throw an exception if it runs out of memory-it never returns NULL. Most compilers implement this correctly, but some do not.

Most examples use protected: data rather than private: data. In the real world, this is appropriate for most developers and most applications, but framework developers probably should not use protected: data, since this would create a data coupling between the derived classes and the protected: data of the base class. In general, framework developers should use private: data with protected: access functions.

Type names (names of classes, structs, unions, enums, and typedefs) start with a capital letter; preprocessor symbols are all capitals; all other identifiers start with a lowercase letter. Data member names and class-scoped enumerations end with a single underscore.

It is assumed that the file extensions .cpp and .hpp are appropriate. Some compilers use a different convention.

Universal Modeling Language (UML) notation is used to express design relationships.

The following priorities were used in designing the examples: (1) unity of purpose, (2) compactness, and (3) self-contained functionality. In other words, each example demonstrates one basic point or technique, is as short as possible, and, if possible, is a complete, working program. The examples are not intended for plug-in reuse in industrial-strength settings because balancing the resultant (subtle) tradeoffs would conflict with these priorities.

To avoid complicating the discussions with finding the optimal balance between the use of virtual and inline for member functions, virtual is used more often than strictly necessary (see FAQ 21.15). To achieve compactness, some member functions are defined in the class body even if they wouldn't normally be inline or even if moving them down to the bottom of a header file would improve specification (see FAQ 6.05). Uncalled functions are often left undefined. Some functions that are called are also undefined, since compactness is a higher priority than self-contained functionality. Also for compactness, examples are not wrapped in preprocessor symbols that prevent multiple expansions (see FAQ 2.16).

The examples put the public: part at the beginning of the class rather than at the end of the class. This makes it easier for those who simply want to use the class as opposed to those who want to go in and change the internal implementation of the class. This is normally the right tradeoff since a class is normally used a lot more often than it is changed.

It is assumed that the C++ compiler and standard library are both compliant with the Standard and work correctly. In the real world, this is probably not a safe assumption, and you should be cautious.

Author Biography:

Marshall Cline is President of MT Systems Company, which develops object-oriented systems for large corporations. He has taught object-oriented programming design and analysis to thousands of professionals in both industrial and academic settings. He is the keeper of the official C++ FAQ for the Internet forum comp.lang.c++. He received the PhD in Electrical and Computer Engineering from Clarkson University.

Greg Lomow is a senior architect and developer with fifteen years of experience building applications and distributed systems for the banking and financial services industry as well as mentoring development teams on the effective use of object-oriented technology. He received the PhD in Computer Science from the University of Calgary.

Mike Girou, Chairman of MT Systems Company, has served on national and international C++ standards committees and has twelv C++ experience. He received the PhD in Mathematics from the University of Missouri at Columbia.

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing 1 Customer Reviews
  • Posted August 23, 2011

    One of the best references for c++

    If you only want to keep one C++ book on your shelf this it. Full of hints, best practices, and gotchas. Very well organized and easy to read.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing 1 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)