C Language

New and Improved

Macros have always been one of C's most flexible tools, and I pointed out in previous chapters how useful they are for paving over some of C's rough spots. The power of macros - and their pitfalls - motivated some of the best new features of C++. Where a better C++ alternative exists, use it instead of a macro.

On the other hand, you'll still find some important uses of macros in C++; for example, using PTR and contents_of macros instead of *, as described in Chapter 6. You can benefit from extending these C macros to cover new C++ features, such as references. The following code uses a simple REF macro to produce easily read code:

 #define REF &
 int REF benefit_age = spouse_age;

This sure beats the non-intuitive

 int& benefit_age = spouse_age;

style of coding you'll find in most C++ tutorials.

C++ offers some other clear improvements over C.Use the C++ new and delete operators instead of the malloc() and free() functions because new allocates memory based on the type of its argument, rather than on an explicit number of bytes. You can also create your own function for new operations on objects of user-defined classes.