C Language

The Calm Before the Storm

Before examining the less pleasant side of C++, let's consider some of the other advantages it offers over C. You can reduce the use of function-like macros, and thus avoid many of the pitfalls I described in Chapter 7, by using in-line functions and templates instead.

Functions defined inside a class or with the in-line specifier can be compiled into in-line code, rather than a normal function call (the decision is left to the compiler). This technique lets you use in-line functions instead of equivalent macros - avoiding macro pitfalls but keeping their performance. Because you can control whether a member function that's defined outside its class declaration is in-line or not, it's good practice to define all member functions outside their respective class declaration. Following this rule also keeps your class definitions more compact and readable. For example, use

 class classX {
    inline int f( void );
 };
 inline int classX::f( void ) {
  ...
 }

rather than

 class classX {
    int f( void ) {
     ...
    }
 };

In general, use in-line functions sparingly. The performance savings from eliminating a function call can easily be lost as code size expands.

C++ templates are another one of its true bright spots. They provide a way to implement a generic piece of code that can work on different data types. This eliminates many of the places in C where a complex macro would be used instead of a function, so that the code can work with more than one type. Templates are also much simpler to use than some of the advanced C++ techniques for writing functions that can handle multiple types.

by BrainBellupdated
Advertisement: