More Books
C++ Gotchas: Avoiding Common Problems in Coding and Design
Main Page
Table of content
Copyright
Addison-Wesley Professional Computing Series
Preface
Acknowledgments
Chapter 1. Basics
Gotcha #1: Excessive Commenting
Gotcha #2: Magic Numbers
Gotcha #3: Global Variables
Gotcha #4: Failure to Distinguish Overloading from Default Initialization
Gotcha #5: Misunderstanding References
Gotcha #6: Misunderstanding Const
Gotcha #7: Ignorance of Base Language Subtleties
Gotcha #8: Failure to Distinguish Access and Visibility
Gotcha #9: Using Bad Language
Gotcha #10: Ignorance of Idiom
Gotcha #11: Unnecessary Cleverness
Gotcha #12: Adolescent Behavior
Chapter 2. Syntax
Gotcha #13: Array/Initializer Confusion
Gotcha #14: Evaluation Order Indecision
Gotcha #15: Precedence Problems
Gotcha #16: 'for' Statement Debacle
Gotcha #17: Maximal Munch Problems
Gotcha #18: Creative Declaration-Specifier Ordering
Gotcha #19: Function/Object Ambiguity
Gotcha #20: Migrating Type-Qualifiers
Gotcha #21: Self-Initialization
Gotcha #22: Static and Extern Types
Gotcha #23: Operator Function Lookup Anomaly
Gotcha #24: Operator '->' Subtleties
Chapter 3. The Preprocessor
Gotcha #25: '#define' Literals
Gotcha #26: '#define' Pseudofunctions
Gotcha #27: Overuse of '#if'
Gotcha #28: Side Effects in Assertions
Chapter 4. Conversions
Gotcha #29: Converting through 'void *'
Gotcha #30: Slicing
Gotcha #31: Misunderstanding Pointer-to-Const Conversion
Gotcha #32: Misunderstanding Pointer-to-Pointer-to-Const Conversion
Gotcha #33: Misunderstanding Pointer-to-Pointer-to-Base Conversion
Gotcha #34: Pointer-to-Multidimensional-Array Problems
Gotcha #35: Unchecked Downcasting
Gotcha #36: Misusing Conversion Operators
Gotcha #37: Unintended Constructor Conversion
Gotcha #38: Casting under Multiple Inheritance
Gotcha #39: Casting Incomplete Types
Gotcha #40: Old-Style Casts
Gotcha #41: Static Casts
Gotcha #42: Temporary Initialization of Formal Arguments
Gotcha #43: Temporary Lifetime
Gotcha #44: References and Temporaries
Gotcha #45: Ambiguity Failure of 'dynamic_cast'
Gotcha #46: Misunderstanding Contravariance
Chapter 5. Initialization
Gotcha #47: Assignment/Initialization Confusion
Gotcha #48: Improperly Scoped Variables
Gotcha #49: Failure to Appreciate C++'s Fixation on Copy Operations
Gotcha #50: Bitwise Copy of Class Objects
Gotcha #51: Confusing Initialization and Assignment in Constructors
Gotcha #52: Inconsistent Ordering of the Member Initialization List
Gotcha #53: Virtual Base Default Initialization
Gotcha #54: Copy Constructor Base Initialization
Gotcha #55: Runtime Static Initialization Order
Gotcha #56: Direct versus Copy Initialization
Gotcha #57: Direct Argument Initialization
Gotcha #58: Ignorance of the Return Value Optimizations
Gotcha #59: Initializing a Static Member in a Constructor
Chapter 6. Memory and Resource Management
Gotcha #60: Failure to Distinguish Scalar and Array Allocation
Gotcha #61: Checking for Allocation Failure
Gotcha #62: Replacing Global New and Delete
Gotcha #63: Confusing Scope and Activation of Member 'new' and 'delete'
Gotcha #64: Throwing String Literals
Gotcha #65: Improper Exception Mechanics
Gotcha #66: Abusing Local Addresses
Gotcha #67: Failure to Employ Resource Acquisition Is Initialization
Gotcha #68: Improper Use of 'auto_ptr'
Chapter 7. Polymorphism
Gotcha #69: Type Codes
Gotcha #70: Nonvirtual Base Class Destructor
Gotcha #71: Hiding Nonvirtual Functions
Gotcha #72: Making Template Methods Too Flexible
Gotcha #73: Overloading Virtual Functions
Gotcha #74: Virtual Functions with Default Argument Initializers
Gotcha #75: Calling Virtual Functions in Constructors and Destructors
Gotcha #76: Virtual Assignment
Gotcha #77: Failure to Distinguish among Overloading, Overriding, and Hiding
Gotcha #78: Failure to Grok Virtual Functions and Overriding
Gotcha #79: Dominance Issues
Chapter 8. Class Design
Gotcha #80: Get/Set Interfaces
Gotcha #81: Const and Reference Data Members
Gotcha #82: Not Understanding the Meaning of Const Member Functions
Gotcha #83: Failure to Distinguish Aggregation and Acquaintance
Gotcha #84: Improper Operator Overloading
Gotcha #85: Precedence and Overloading
Gotcha #86: Friend versus Member Operators
Gotcha #87: Problems with Increment and Decrement
Gotcha #88: Misunderstanding Templated Copy Operations
Chapter 9. Hierarchy Design
Gotcha #89: Arrays of Class Objects
Gotcha #90: Improper Container Substitutability
Gotcha #91: Failure to Understand Protected Access
Gotcha #92: Public Inheritance for Code Reuse
Gotcha #93: Concrete Public Base Classes
Gotcha #94: Failure to Employ Degenerate Hierarchies
Gotcha #95: Overuse of Inheritance
Gotcha #96: Type-Based Control Structures
Gotcha #97: Cosmic Hierarchies
Gotcha #98: Asking Personal Questions of an Object
Gotcha #99: Capability Queries
Bibliography

Gotcha #37: Unintended Constructor Conversion

A single-argument constructor specifies both an initialization and a conversion. As with a conversion operator, a constructor conversion may be applied implicitly by the compiler. This is sometimes convenient:

class String { 
 public:
   String( const char * );
   operator const char *() const;
   // . . .
};
String name1( "Fred" ); // direct init
name1 = "Joe"; // implicit conversion
const char *cname = name1; // implicit conversion
String name2 = cname; // implicit conversion, copy init
String name3 = String( cname ); // explicit conversion, copy init

(See Gotcha #56.) However, implicit constructor conversions can often render code hard to understand and can introduce obscure bugs. Consider a container template for a stack of fixed, maximum size:

template <class T> 
class BoundedStack {
 public:
   BoundedStack( int maxSize );
   ~BoundedStack();
   bool operator ==( const BoundedStack & ) const;
   void push( const T & );
   void pop();
   const T &top() const;
   // . . .
};

Our BoundedStack types have the usual stack operations of push, pop, and so on, as well as the ability to compare two stacks for equality. When we create a BoundedStack<T>, we must provide its maximum size.

BoundedStack<double> s( 128 ); 
s.push( 37.0 );
s.push( 232.78 );
// . . .

Unfortunately, the single-argument constructor may be applied as a conversion in cases where we would probably have preferred a compile-time error:

if( s == 37 ) { // oops! 
   // . . .

In this case, chances are that we intended to have a condition like s.top() == 37. Unfortunately, the condition will compile without error, because the compiler is able to convert the integer value 37 into a BoundedStack<double> and pass it as an argument to BoundedStack<double>::operator ==. Effectively, the compiler generates the following code:

BoundedStack<double> stackTemp( 37 ); 
bool resultTemp( s.operator ==( stackTemp ) );
stackTemp.~BoundedStack<double>();
if( resultTemp ) {
   // . . .

The resulting code is legal, incorrect, and expensive. A safer alternative would be to declare the BoundedStack constructor to be explicit. The explicit keyword tells the compiler that it may not use the constructor as an implicit conversion, although it may still be used as an explicit conversion:

template <class T> 
class BoundedStack {
 public:
   explicit BoundedStack( int maxSize );
   // . . .
};
// . . .
if( s == 37 ) { // error, fortunately
   // . . .
if( s.top() == 37 ) { // correct, no conversion
   // . . .
if( s == static_cast< BoundedStack<double> >(37) ) { // correct . . .
   // . . .

Insidious implicit conversions are much more to be feared than the occasional necessity of performing an explicit conversion, so it's common and recommended to declare most single-argument constructors explicit.

Note that declaring a constructor explicit also affects the set of legal initialization syntaxes one may employ when declaring an object of a class. Let's make a change to our String class above and see how it affects the set of legal initializations:

class String { 
 public:
   explicit String( const char * );
   operator const char *() const;
   // . . .
};
String name1( "Fred" ); // OK.
name1 = "Joe"; // error!
const char *cname = name1; // implicit conversion, OK
String name2 = cname; // error!
String name3 = String( cname ); // explicit conversion, OK

The implicit temporary generation that is part of the copy initializations of name2 and the argument of String::operator = are now illegal. The initialization of name3 is still legal, because the conversion is explicit (although it would have been better form to perform the initialization with a static_cast; see Gotcha #40). As usual, it's best to use direct initialization in preference to copy initialization. (See Gotcha #56.)

Before we leave the subject of explicit behind, let's have a look at an instructive, but now outmoded, technique for implementing the semantics of explicit without use of the keyword:

class StackInit { 
 public:
   StackInit( size_t s ) : size_( s ) {}
   int getSize() const { return size_; }
 private:
   int size_;
};
template <class T>
class BoundedStack {
 public:
   BoundedStack( const StackInit &init );
   // . . .
};

Because the BoundedStack constructor isn't declared to be explicit, the compiler will attempt to convert implicitly any StackInit objects to BoundedStack. However, the compiler won't make the attempt to convert an integer to a StackInit and follow that implicit conversion with a second implicit conversion of StackInit to BoundedStack. The standard specifies that the compiler will attempt only a single implicit user-defined conversion at a time:

BoundedStack<double> s( 128 ); // OK. 
BoundedStack<double> t = 128; // OK.
if( s == 37 ) { // error!
   // . . .

This technique gives us behavior almost identical to that of explicit. The declaration of s and t is legal, because only a single user-defined conversion is necessary to convert 128 into a StackInit to pass to the constructor. However, the compiler will not attempt to convert 37 to a BoundedStack<double>, because that would require a sequence of two user-defined conversions: int to StackInit and StackInit to BoundedStack<double>.