February 21, 1998

Prefer Enums Over #define Macros When You Need a Fixed Set of Values

Instead of using #define macros to create a set of values, as in this (deprecated) example: #define JAN 1#define FEB 2//…#define DEC 12 Enum types are a significantly better choice: //file enums.henum Months { //a list of enumerators: Jan, Feb, //… Dec };enum Days { Sun, Mon, //… }; There

Conversion Operators

Sometimes, an object must be converted into a built-in type (for instance, a string object passed as an argument to C function such as strcmp()) : //file Mystring.hclass Mystring { char *s; int size; public: Mystring(const char *); Mystring(); //…};#include //C str- family of functions#include Mystring.hvoid main() {Mystring str(hello world);int

Correct syntax for automatic object instantiation

When you instantiate an automatic object (e.g., on the stack) using its default constructor, mind that the correct syntax is: String str; //correct And not this: String str(); //entirely different meaning Can you see why? The second statement is parsed as a declaration:

IsA or HasA?

When designing a class hierarchy, you may face a decision between inheritance (aka IsA ) vs. containment (aka HasA) relation. For instance, if you are designing a Radio class, and you already have the following classes implemented for you in some library: Dial, ElectricAppliance. It is quite obvious that your

A base class destructor should be virtual

If a class may serve as a base class for others, its destructor should be virtual. This ensures RTTI support for objects of this class and objects derived from it, and more important, you ensure that the correct destructor is always called, even in the following case: class Base{ char