|
| 1 | + |
| 2 | +# C++ QUICK REFERENCE / C++ CHEATSHEET |
| 3 | +Based on <a href="http://www.pa.msu.edu/~duxbury/courses/phy480/Cpp_refcard.pdf">Phillip M. Duxbury's C++ Cheatsheet</a> and edited by Morten Nobel-Jørgensen. |
| 4 | +The cheatsheet focus on C++ - not on the library. |
| 5 | +C++11 additions is inspired by <a href="https://isocpp.org/blog/2012/12/c11-a-cheat-sheet-alex-sinyakov">ISOCPP.org C++11 Cheatsheet</a>). |
| 6 | + |
| 7 | +The goal is to give a concise overview of basic, modern C++. |
| 8 | + |
| 9 | +The document is hosted on XXX. Any comments and feedback are appreciated. |
| 10 | + |
| 11 | +## PREPROCESSOR |
| 12 | + |
| 13 | +~~~~ |
| 14 | + // Comment to end of line |
| 15 | + /* Multi-line comment */ |
| 16 | +#include <stdio.h> // Insert standard header file |
| 17 | +include "myfile.h" // Insert file in current directory |
| 18 | +#define X some text // Replace X with some text |
| 19 | +#define F(a,b) a+b // Replace F(1,2) with 1+2 |
| 20 | +#define X \ |
| 21 | + some text // Multiline definition |
| 22 | +#undef X // Remove definition |
| 23 | +#if defined(X) // Condional compilation (#ifdef X) |
| 24 | +#else // Optional (#ifndef X or #if !defined(X)) |
| 25 | +#endif // Required after #if, #ifdef |
| 26 | +~~~~ |
| 27 | + |
| 28 | +## LITERALS |
| 29 | +~~~~ |
| 30 | +255, 0377, 0xff // Integers (decimal, octal, hex) |
| 31 | +2147483647L, 0x7fffffffl // Long (32-bit) integers |
| 32 | +123.0, 1.23e2 // double (real) numbers |
| 33 | +'a', '\141', '\x61' // Character (literal, octal, hex) |
| 34 | +'\n', '\\', '\'', '\"' // Newline, backslash, single quote, double quote |
| 35 | +"string\n" // Array of characters ending with newline and \0 |
| 36 | +"hello" "world" // Concatenated strings |
| 37 | +true, false // bool constants 1 and 0 |
| 38 | +nullptr // Pointer type with the address of 0 |
| 39 | +~~~~ |
| 40 | + |
| 41 | +## DECLARATIONS |
| 42 | +~~~~ |
| 43 | +int x; // Declare x to be an integer (value undefined) |
| 44 | +int x=255; // Declare and initialize x to 255 |
| 45 | +short s; long l; // Usually 16 or 32 bit integer (int may be either) |
| 46 | +char c='a'; // Usually 8 bit character |
| 47 | +unsigned char u=255; |
| 48 | +signed char s=-1; // char might be either |
| 49 | +unsigned long x = |
| 50 | + 0xffffffffL; // short, int, long are signed |
| 51 | +float f; double d; // Single or double precision real (never unsigned) |
| 52 | +bool b=true; // true or false, may also use int (1 or 0) |
| 53 | +int a, b, c; // Multiple declarations |
| 54 | +int a[10]; // Array of 10 ints (a[0] through a[9]) |
| 55 | +int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; ) |
| 56 | +int a[2][2]={{1,2},{4,5}}; // Array of array of ints |
| 57 | +char s[]="hello"; // String (6 elements including '\0') |
| 58 | +std::string s = "Hello" // Creates string object with value "Hello" |
| 59 | +std::string s = R"(Hello |
| 60 | +World)"; // Creates string object with value "Hello\nWorld" |
| 61 | +int* p; // p is a pointer to (address of) int |
| 62 | +char* s="hello"; // s points to unnamed array containing "hello" |
| 63 | +void* p=nullptr; // Address of untyped memory (nullptr is 0) |
| 64 | +int& r=x; // r is a reference to (alias of) int x |
| 65 | +enum weekend {SAT,SUN}; // weekend is a type with values SAT and SUN |
| 66 | +enum weekend day; // day is a variable of type weekend |
| 67 | +enum weekend{SAT=0,SUN=1}; // Explicit representation as int |
| 68 | +enum {SAT,SUN} day; // Anonymous enum |
| 69 | +enum class Color {Red,Blue};// Color is a strict type with values Red and Blue |
| 70 | +Color x = Color::Red; // Assign Color x to red |
| 71 | +typedef String char*; // String s; means char* s; |
| 72 | +const int c=3; // Constants must be initialized, cannot assign to |
| 73 | +const int* p=a; // Contents of p (elements of a) are constant |
| 74 | +int* const p=a; // p (but not contents) are constant |
| 75 | +const int* const p=a; // Both p and its contents are constant |
| 76 | +const int& cr=x; // cr cannot be assigned to change x |
| 77 | +int8_t,uint8_t,int16_t, |
| 78 | +uint16_t,int32_t,uint32_t, |
| 79 | +int64_t,uint64_t // Fixed length standard types |
| 80 | +auto it = m.begin(); // Declares it to the result of m.begin() |
| 81 | +auto const param = config["param"]; |
| 82 | + // Declares it to the const result |
| 83 | +auto& s = singleton::instance(); |
| 84 | + // Declares it to a reference of the result |
| 85 | +~~~~ |
| 86 | + |
| 87 | +## STORAGE CLASSES |
| 88 | +~~~~ |
| 89 | +int x; // Auto (memory exists only while in scope) |
| 90 | +static int x; // Global lifetime even if local scope |
| 91 | +extern int x; // Information only, declared elsewhere |
| 92 | +~~~~ |
| 93 | + |
| 94 | +## STATEMENTS |
| 95 | +~~~~ |
| 96 | +x=y; // Every expression is a statement |
| 97 | +int x; // Declarations are statements |
| 98 | +; // Empty statement |
| 99 | +{ // A block is a single statement |
| 100 | + int x; // Scope of x is from declaration to end of block |
| 101 | +} |
| 102 | +if (x) a; // If x is true (not 0), evaluate a |
| 103 | +else if (y) b; // If not x and y (optional, may be repeated) |
| 104 | +else c; // If not x and not y (optional) |
| 105 | +
|
| 106 | +while (x) a; // Repeat 0 or more times while x is true |
| 107 | +
|
| 108 | +for (x; y; z) a; // Equivalent to: x; while(y) {a; z;} |
| 109 | +
|
| 110 | +for (x : y) a; // Range-based for loop e.g. |
| 111 | + // for (auto& x in someList) x.y(); |
| 112 | +
|
| 113 | +do a; while (x); // Equivalent to: a; while(x) a; |
| 114 | +
|
| 115 | +switch (x) { // x must be int |
| 116 | + case X1: a; // If x == X1 (must be a const), jump here |
| 117 | + case X2: b; // Else if x == X2, jump here |
| 118 | + default: c; // Else jump here (optional) |
| 119 | +} |
| 120 | +break; // Jump out of while, do, or for loop, or switch |
| 121 | +continue; // Jump to bottom of while, do, or for loop |
| 122 | +return x; // Return x from function to caller |
| 123 | +try { a; } |
| 124 | +catch (T t) { b; } // If a throws a T, then jump here |
| 125 | +catch (...) { c; } // If a throws something else, jump here |
| 126 | +~~~~ |
| 127 | + |
| 128 | +## FUNCTIONS |
| 129 | +~~~~ |
| 130 | +int f(int x, int); // f is a function taking 2 ints and returning int |
| 131 | +void f(); // f is a procedure taking no arguments |
| 132 | +void f(int a=0); // f() is equivalent to f(0) |
| 133 | +f(); // Default return type is int |
| 134 | +inline f(); // Optimize for speed |
| 135 | +f() { statements; } // Function definition (must be global) |
| 136 | +T operator+(T x, T y); // a+b (if type T) calls operator+(a, b) |
| 137 | +T operator-(T x); // -a calls function operator-(a) |
| 138 | +T operator++(int); // postfix ++ or -- (parameter ignored) |
| 139 | +extern "C" {void f();} // f() was compiled in C |
| 140 | +~~~~ |
| 141 | + |
| 142 | +Function parameters and return values may be of any type. A function must either be declared or defined before |
| 143 | +it is used. It may be declared first and defined later. Every program consists of a set of a set of global variable |
| 144 | +declarations and a set of function definitions (possibly in separate files), one of which must be: |
| 145 | + |
| 146 | +~~~~ |
| 147 | +int main() { statements... } or |
| 148 | +int main(int argc, char* argv[]) { statements... } |
| 149 | +~~~~ |
| 150 | + |
| 151 | +argv is an array of argc strings from the command line. By convention, main returns status 0 if successful, 1 or |
| 152 | +higher for errors. |
| 153 | + |
| 154 | +Functions with different parameters may have the same name (overloading). Operators except :: . .* ?: may be |
| 155 | +overloaded. Precedence order is not affected. New operators may not be created. |
| 156 | + |
| 157 | +## EXPRESSIONS |
| 158 | +Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All |
| 159 | +others are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time |
| 160 | +checks for arrays out of bounds, invalid pointers, etc. |
| 161 | + |
| 162 | +~~~~ |
| 163 | +T::X // Name X defined in class T |
| 164 | +N::X // Name X defined in namespace N |
| 165 | +::X // Global name X |
| 166 | +
|
| 167 | +t.x // Member x of struct or class t |
| 168 | +p-> x // Member x of struct or class pointed to by p |
| 169 | +a[i] // i'th element of array a |
| 170 | +f(x,y) // Call to function f with arguments x and y |
| 171 | +T(x,y) // Object of class T initialized with x and y |
| 172 | +x++ // Add 1 to x, evaluates to original x (postfix) |
| 173 | +x-- // Subtract 1 from x, evaluates to original x |
| 174 | +typeid(x) // Type of x |
| 175 | +typeid(T) // Equals typeid(x) if x is a T |
| 176 | +dynamic_cast< T>(x) // Converts x to a T, checked at run time |
| 177 | +static_cast< T>(x) // Converts x to a T, not checked |
| 178 | +reinterpret_cast< T>(x) // Interpret bits of x as a T |
| 179 | +const_cast< T>(x) // Converts x to same type T but not const |
| 180 | +
|
| 181 | +sizeof x // Number of bytes used to represent object x |
| 182 | +sizeof(T) // Number of bytes to represent type T |
| 183 | +++x // Add 1 to x, evaluates to new value (prefix) |
| 184 | +--x // Subtract 1 from x, evaluates to new value |
| 185 | +~x // Bitwise complement of x |
| 186 | +!x // true if x is 0, else false (1 or 0 in C) |
| 187 | +-x // Unary minus |
| 188 | ++x // Unary plus (default) |
| 189 | +&x // Address of x |
| 190 | +*p // Contents of address p (*&x equals x) |
| 191 | +new T // Address of newly allocated T object |
| 192 | +new T(x, y) // Address of a T initialized with x, y |
| 193 | +new T[x] // Address of allocated n-element array of T |
| 194 | +delete p // Destroy and free object at address p |
| 195 | +delete[] p // Destroy and free array of objects at p |
| 196 | +(T) x // Convert x to T (obsolete, use .._cast<T>(x)) |
| 197 | +
|
| 198 | +x * y // Multiply |
| 199 | +x / y // Divide (integers round toward 0) |
| 200 | +x \% y // Modulo (result has sign of x) |
| 201 | +\\ |
| 202 | +x + y // Add, or \&x[y] |
| 203 | +x - y // Subtract, or number of elements from *x to *y |
| 204 | +x << y // x shifted y bits to left (x * pow(2, y)) |
| 205 | +x >> y // x shifted y bits to right (x / pow(2, y)) |
| 206 | +
|
| 207 | +x < y // Less than |
| 208 | +x <= y // Less than or equal to |
| 209 | +x > y // Greater than |
| 210 | +x >= y // Greater than or equal to |
| 211 | +
|
| 212 | +x & y // Bitwise and (3 & 6 is 2) |
| 213 | +x ^ y // Bitwise exclusive or (3 ^ 6 is 5) |
| 214 | +x | y // Bitwise or (3 | 6 is 7) |
| 215 | +x && y // x and then y (evaluates y only if x (not 0)) |
| 216 | +x || y // x or else y (evaluates y only if x is false (0)) |
| 217 | +x = y // Assign y to x, returns new value of x |
| 218 | +x += y // x = x + y, also -= *= /= <<= >>= &= |= ^= |
| 219 | +x ? y : z // y if x is true (nonzero), else z |
| 220 | +throw x // Throw exception, aborts if not caught |
| 221 | +x , y // evaluates x and y, returns y (seldom used) |
| 222 | +~~~~ |
| 223 | + |
| 224 | +## CLASSES |
| 225 | +~~~~ |
| 226 | +class T { // A new type |
| 227 | +private: // Section accessible only to T's member functions |
| 228 | +protected: // Also accessable to classes derived from T |
| 229 | +public: // Accessable to all |
| 230 | + int x; // Member data |
| 231 | + void f(); // Member function |
| 232 | + void g() {return;} // Inline member function |
| 233 | + void h() const; // Does not modify any data members |
| 234 | + int operator+(int y); // t+y means t.operator+(y) |
| 235 | + int operator-(); // -t means t.operator-() |
| 236 | + T(): x(1) {} // Constructor with initialization list |
| 237 | + T(const T& t): x(t.x) {}// Copy constructor |
| 238 | + T& operator=(const T& t) |
| 239 | + {x=t.x; return *this; } // Assignment operator |
| 240 | + ~T(); // Destructor (automatic cleanup routine) |
| 241 | + explicit T(int a); // Allow t=T(3) but not t=3 |
| 242 | + T(float x): T((int)x) {}// Delegate contructor to T(int) |
| 243 | + operator int() const |
| 244 | + {return x;} // Allows int(t) |
| 245 | + friend void i(); // Global function i() has private access |
| 246 | + friend class U; // Members of class U have private access |
| 247 | + static int y; // Data shared by all T objects |
| 248 | + static void l(); // Shared code. May access y but not x |
| 249 | + class Z {}; // Nested class T::Z |
| 250 | + typedef int V; // T::V means int |
| 251 | +}; |
| 252 | +void T::f() { // Code for member function f of class T |
| 253 | + this->x = x;} // this is address of self (means x=x;) |
| 254 | +int T::y = 2; // Initialization of static member (required) |
| 255 | +T::l(); // Call to static member |
| 256 | +T t; // Create object t implicit call constructor |
| 257 | +t.f(); // Call method f on object t |
| 258 | + |
| 259 | +struct T { // Equivalent to: class T { public: |
| 260 | + virtual void i(); // May be overridden at run time by derived class |
| 261 | + virtual void g()=0; }; // Must be overridden (pure virtual) |
| 262 | +class U: public T { // Derived class U inherits all members of base T |
| 263 | + public: |
| 264 | + void g(int) override; }; // Override method g |
| 265 | +class V: private T {}; // Inherited members of T become private |
| 266 | +class W: public T, public U {}; |
| 267 | + // Multiple inheritance |
| 268 | +class X: public virtual T {}; |
| 269 | + // Classes derived from X have base T directly |
| 270 | +~~~~ |
| 271 | + |
| 272 | +All classes have a default copy constructor, assignment operator, and destructor, which perform the |
| 273 | +corresponding operations on each data member and each base class as shown above. There is also a default no-argument |
| 274 | +constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and |
| 275 | +destructors do not inherit. |
| 276 | + |
| 277 | +## TEMPLATES |
| 278 | +~~~~ |
| 279 | +template <class T> T f(T t);// Overload f for all types |
| 280 | +template <class T> class X {// Class with type parameter T |
| 281 | + X(T t); }; // A constructor |
| 282 | +template <class T> X<T>::X(T t) {} |
| 283 | + // Definition of constructor |
| 284 | +X<int> x(3); // An object of type "X of int" |
| 285 | +template <class T, class U=T, int n=0> |
| 286 | + // Template with default parameters |
| 287 | +~~~~ |
| 288 | + |
| 289 | +## NAMESPACES |
| 290 | +~~~~ |
| 291 | +namespace N {class T {};} // Hide name T |
| 292 | +N::T t; // Use name T in namespace N |
| 293 | +using namespace N; // Make T visible without N:: |
| 294 | +~~~~ |
| 295 | + |
0 commit comments