User:Mikethegreen/C++ Tips

From Wikipedia, the free encyclopedia

Contents

[edit] C++ Tips

[edit] Read pointer declarations from right to left

const Foo *x;         // x is a pointer to a const Foo
Foo const *x;         // same as above
 
Foo * const y;        // y is a const pointer to a Foo
 
const Foo * const z;  // z is a const pointer to a const Foo

[edit] '::' is good style to identify calls to functions in the global namespace

// RegOpenKeyEx is globally defined
::RegOpenKeyEx(HKEY_LOCAL_MACHINE, sKey.c_str(), 0, KEY_READ, &hKey);

[edit] Order of includes is important

// B.h depends on A.h
#include "A.h"
#include "B.h" // must come after A.h

[edit] Class declarations end with a ';', can cause strange errors if you forget

// File: A.h
class A
{
    public:
        A();
}
  • Compile error will occur in files that include A.h
// File: A.cpp
#include "A.h"
 
A::A()
{
 
}

[edit] Link library dependencies

A DLL project that references a static library project should use the "link library dependencies" option to automatically link the .libs of the parent.

[edit] Translation Unit

  • Translation unit = Headers + 1 source file