Sunday, June 3, 2007

Item 2

prefer consts enums and inline to #define

strings are preferable to const char*

so const std::string author("scott meyers");

is preferable to
const char * const author = "scott meyers"

class gamePlayer
static const int numTurns = 5;
int scores[numTurns];

above is just a declaration for numTurns and not a definition.

c++ allows u to use after declaring only if its a static int and its address isnt taken.

if you take address of a class, then you have to define it also:

const int GamePlayer::numTurns;--- this goes in impl file not header file

in class initialization is allowed only for const ints.


const costEstimate
static const double fudgeFactor ;

const double constEstimate::fudgeFactor = 1.35;

how to get the value if you need it for compilation, as in the first class where you needed it to create the array: ( some compilers dont allow declaring value inside the class so you cannt use style of 1 )

class gamePlayer{
enum { numTurns = 5};
int scores[numTurns];


it is known as the enum hack.

it allows you to make sure people cannt get a reference to your constants.
it also makes sure compilers wont allocate any memory for it.

can people access that value or you can just declare a private enum ?

why wud the value not get picked up if it is cost Estimate style ?

try not to use macros at all. you can get all the efficiency of a macro with the type safety of a regular function by using templates for an inline functions.

#define call_with_max(a,b) f((a) >(b) ? (a) : (b) )

replace with

inline void callWithMax( const T&a , cons t T&b )
f ( a> b ? a:b);

preprocessor is bad but we need #include and #ifndef and #define
things to remember from this article:

for simple constants prefer const objects to enums to #defines
for function like macros prefer inline functions to #defines

No comments: