C++ Cheat Sheet
Quick reference from FreeCodingCourses.com
Variables and types
int x = 5;- an integer. Semicolons end statements.
double d = 3.14; bool ok = true;- other basics. char c = 'a';
auto n = 5;- let the compiler infer the type.
const int MAX = 100;- a constant.
std::string s = "hi";- a string. #include <string>.
Input and output
#include <iostream>- for cout and cin.
std::cout << "Hi " << name << "\n";- print to the console.
std::cin >> x;- read a value from input.
using namespace std;- lets you drop the std:: prefix (common in tutorials).
Vectors and strings
std::vector<int> xs = {1, 2, 3};- a growable array. #include <vector>.
xs.push_back(4); xs.size();- add to the end, count.
xs[0] xs.at(0)- index. .at() checks bounds, [] does not.
for (int x : xs) { ... }- range-based loop over items.
s.length() s.substr(0, 3)- string length and slice.
References and pointers
int& r = x;- a reference: another name for x.
void inc(int& n) { n++; }- pass by reference to change the caller's value.
int* p = &x;- a pointer holds an address. & takes the address.
*p = 10;- dereference: read or write what p points to.
auto p = std::make_unique<User>();- a smart pointer that frees itself.
Control flow
if (x > 0) { ... } else { ... }- parentheses and braces.
for (int i = 0; i < 5; i++) { ... }- counted loop.
while (cond) { ... }- loop while true.
switch (x) { case 1: ...; break; default: ...; }- remember break, or cases fall through.
Classes
class User { public: std::string name; };- a class. Note the trailing semicolon.
User(std::string n) : name(n) {}- a constructor with an initializer list.
std::string greet() { return "Hi"; }- a member function.
User u("Ada"); u.greet();- create an object and call a method.
Unlock the full C++ cheat sheet
You're seeing 2 of 6 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.