The Ultimate C++ Cheat Sheet

C++ is a powerful and widely used programming language, but it can also be complex and overwhelming for beginners or those who are not frequent users. With so many features, syntax rules, and libraries, it can be challenging to remember everything. That’s where a cheat sheet comes in handy. This “Ultimate C++ Cheat Sheet” is designed to be a quick reference for C++ programmers of all levels. It covers the essential elements of the language, including syntax, keywords, data types, functions, and more. Whether you’re a seasoned C++ developer or just starting out, this cheat sheet will be a valuable resource to keep at your fingertips.

C++ Basic syntax

Comments

Used to add notes or explanations to the code, and are ignored by the compiler.

// Single-line comment
/* Multi-line comment */

Data Types

Specify the type of value a variable can store.

int - for integers
float - for floating point numbers
double - for double precision floating point numbers
char - for single characters
bool - for boolean values (true or false)

Variables

Used to store values in memory. Declared with a data type and given a unique name.

int age = 30;
float height = 6.2;
char initial = 'J';

Printing to the console

cout << "Hello, World!";

Standard Input

Reading values from the user.

int number;
cin >> number;

End of Line (EOL) and End of File (EOF)

The EOL character marks the end of a line of text and the EOF character marks the end of input from the keyboard. To indicate the end of input, type “Ctrl + Z” in Windows and “Ctrl + D” in Unix/Linux.

Note: This is just a basic overview of C++ syntax, and there is much more to learn. But, this cheat sheet should help you get started with the basics of the language.

C++ Operators, expressions, and control structures

Operators

Used to perform operations on values.

Arithmetic Operators: +, -, *, /, % (modulus)
Relational Operators: ==, !=, >, <, >=, <=
Logical Operators: && (and), || (or), ! (not)
Assignment Operators: =, +=, -=, *=, /=, %=

Expressions

A combination of values, variables, and operators.

int x = 10, y = 5;
int result = x + y;

Control Structures

Used to control the flow of a program.

if-else Statement

int score = 80;
if (score >= 60) {
cout << "Passed";
} else {
cout << "Failed";
}

while Loop

int i = 1;
while (i <= 10) {
cout << i << " ";
i++;
}

for Loop

for (int i = 1; i <= 10; i++) {
cout << i << " ";
}

do-while Loop

int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 10);

Note: This is just a basic overview of C++ operators, expressions, and control structures. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ Functions and parameters

Functions

A set of instructions that perform a specific task.

Function syntax :

return_type function_name(parameter1, parameter2, ...) {
   // function body
}

Example :

int add(int a, int b) {
   return a + b;
}

Function Prototypes

A declaration of a function that specifies the function’s name, return type, and parameters.

Function Prototype Syntax:

return_type function_name(parameter1, parameter2, ...);

Example :

int add(int, int);

Call by Value

A method of passing arguments to a function where the value of the argument is passed. Changes made to the argument inside the function will not affect the original value.

Example:

void increment(int a) {
   a++;
}

int main() {
   int x = 10;
   increment(x);
   cout << x; // Output: 10
}

Call by Reference

A method of passing arguments to a function where the reference (address) of the argument is passed. Changes made to the argument inside the function will affect the original value.

Example:

void increment(int &a) {
   a++;
}

int main() {
   int x = 10;
   increment(x);
   cout << x; // Output: 11
}

Note: This is just a basic overview of C++ functions and parameters. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ Arrays, strings, and pointers

Arrays

A collection of elements of the same data type.

Array Syntax:

data_type array_name[array_size];

Example :

int numbers[5];

Strings

A sequence of characters.

String Syntax:

#include <string>
string str = "Hello World";

Pointers

A variable that holds the memory address of another variable.

Pointer Syntax:

data_type *pointer_name;

Example :

int x = 10;
int *p = &x;

Note: This is just a basic overview of C++ arrays, strings, and pointers. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ Classes and objects

Classes

A blueprint that defines the variables and functions of a specific type of object.

Class Syntax:

class class_name {
   private:
      // variables and functions accessible only within the class
   public:
      // variables and functions accessible from outside the class
};

Objects

An instance of a class.

Object Syntax:

class_name object_name;

Example :

class Rectangle {
   public:
      int length;
      int width;
};

Rectangle rect;
rect.length = 10;
rect.width = 5;

Inheritance

A mechanism where a new class can be derived from an existing class. The new class inherits all the variables and functions of the existing class.

Inheritance Syntax:

class derived_class_name : access_specifier base_class_name {
   // variables and functions of the derived class
};

Example :

class Shape {
   public:
      int area;
};

class Rectangle : public Shape {
   public:
      int length;
      int width;
};

Polymorphism

A mechanism where a single function or operator can be used with objects of different classes.

Example:

class Shape {
   public:
      virtual int area() { return 0; }
};

class Rectangle : public Shape {
   public:
      int length;
      int width;
      int area() { return length * width; }
};

class Circle : public Shape {
   public:
      int radius;
      int area() { return 3.14 * radius * radius; }
};

int main() {
   Shape *shapes[2];
   shapes[0] = new Rectangle();
   shapes[1] = new Circle();
   for (int i = 0; i < 2; i++) {
      cout << shapes[i]->area() << endl;
   }
   return 0;
}

Encapsulation

A mechanism where the variables and functions of a class are combined and hidden from the outside world.

Encapsulation Syntax:

class class_name {
   private:
      int variable;
   public:
      int getVariable() { return variable; }
      void setVariable(int v) { variable = v; }
};

Example :

class Circle {
   private:
      int radius;
   public:
      int getRadius() { return radius; }
      void setRadius(int r) { radius = r; }
};

int main() {
   Circle circle;
   circle.setRadius(10);
   cout << circle.getRadius(); // Output: 10
   return 0;
}

Note: This is just a basic overview of C++ classes and objects. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ Templates and exceptions

Templates

A mechanism to generate functions or classes that work with different data types.

Template Syntax:

template <typename T>
T maximum(T x, T y) {
   return (x > y) ? x : y;
}

Example :

#include <iostream>

template <typename T>
T maximum(T x, T y) {
   return (x > y) ? x : y;
}

int main() {
   cout << maximum(10, 20) << endl; // Output: 20
   cout << maximum(10.5, 20.5) << endl; // Output: 20.5
   return 0;
}

Exceptions

A mechanism to handle errors and unexpected situations in a program.

Exception Syntax:

try {
   // code that might throw an exception
} catch (exception_type e) {
   // code to handle the exception
}

Example :

#include <iostream>
#include <exception>

int divide(int x, int y) {
   if (y == 0) {
      throw std::invalid_argument("division by zero");
   }
   return x / y;
}

int main() {
   try {
      int result = divide(10, 0);
      cout << result << endl;
   } catch (std::invalid_argument &e) {
      cout << e.what() << endl; // Output: division by zero
   }
   return 0;
}

Note: This is just a basic overview of C++ templates and exceptions. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ Standard Template Library (STL) and algorithms

Standard Template Library (STL)

A collection of template classes and functions that provide common data structures and algorithms.

Common STL Data Structures:

  • vector: A dynamic array that can grow or shrink dynamically.
  • list: A doubly linked list.
  • deque: A double-ended queue that allows elements to be added or removed from either end.
  • set: A collection of unique elements stored in a sorted order.
  • map: A collection of key-value pairs stored in a sorted order based on the keys.

Example:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
   std::vector<int> numbers = {1, 2, 3, 4, 5};
   std::sort(numbers.begin(), numbers.end());
   for (int x : numbers) {
      cout << x << " "; // Output: 1 2 3 4 5
   }
   return 0;
}

Algorithms

A collection of functions that operate on STL data structures.

Common STL Algorithms:

  • sort: Sorts the elements of a container.
  • binary_search: Searches for an element in a sorted container.
  • count: Counts the number of occurrences of an element in a container.
  • max_element: Returns the maximum element in a container.
  • min_element: Returns the minimum element in a container.

Example:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
   std::vector<int> numbers = {1, 2, 3, 4, 5};
   int count = std::count(numbers.begin(), numbers.end(), 3);
   cout << count << endl; // Output: 1
   return 0;
}

Note: This is just a basic overview of the C++ Standard Template Library (STL) and algorithms. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ File input/output (I/O)

File Input/Output in C++

A way to read from or write to files on disk.

File Input:

  • ifstream: A class for reading from files.

Example:

#include <iostream>
#include <fstream>
#include <string>

int main() {
   std::ifstream file("example.txt");
   std::string line;
   while (std::getline(file, line)) {
      cout << line << endl;
   }
   file.close();
   return 0;
}

File Output:

  • ofstream: A class for writing to files.

Example:

#include <iostream>
#include <fstream>
#include <string>

int main() {
   std::ofstream file("example.txt");
   file << "Hello, world!" << endl;
   file.close();
   return 0;
}

File I/O Modes

There are several different modes you can use to open a file for input or output.

Modes:

  • ios::in: Open the file for input.
  • ios::out: Open the file for output.
  • ios::app: Open the file for output, and write to the end of the file.
  • ios::trunc: Truncate the file to zero length, or create the file if it does not exist.
  • ios::binary: Open the file in binary mode.

Example:

#include <iostream>
#include <fstream>
#include <string>

int main() {
   std::ofstream file("example.txt", std::ios::app);
   file << "Hello, world!" << endl;
   file.close();
   return 0;
}

Note: This is just a basic overview of file input/output in C++. There is much more to learn, but this cheat sheet should help you get started with the basics.

C++ Dynamic memory allocation and deallocation

Dynamic Memory Allocation

A way to allocate memory dynamically, at runtime.

  • new operator: Allocates memory dynamically.

Example:

#include <iostream>

int main() {
   int *ptr = new int;
   *ptr = 42;
   std::cout << *ptr << std::endl;
   delete ptr;
   return 0;
}
  • new[] operator: Allocates memory for an array dynamically.

Example:

#include <iostream>

int main() {
   int *ptr = new int[10];
   for (int i = 0; i < 10; i++) {
      ptr[i] = i * i;
   }
   for (int i = 0; i < 10; i++) {
      std::cout << ptr[i] << std::endl;
   }
   delete[] ptr;
   return 0;
}

Dynamic Memory Deallocation

A way to deallocate memory dynamically, at runtime.

  • delete operator: Deallocates memory dynamically.

Example:

#include <iostream>

int main() {
   int *ptr = new int;
   *ptr = 42;
   std::cout << *ptr << std::endl;
   delete ptr;
   return 0;
}
  • delete[] operator: Deallocates memory for an array dynamically.

Example:

#include <iostream>

int main() {
   int *ptr = new int[10];
   for (int i = 0; i < 10; i++) {
      ptr[i] = i * i;
   }
   for (int i = 0; i < 10; i++) {
      std::cout << ptr[i] << std::endl;
   }
   delete[] ptr;
   return 0;
}

Note: This is just a basic overview of dynamic memory allocation and deallocation in C++. There is much more to learn, but this cheat sheet should help you get started with the basics.

Tips and tricks for optimizing C++ code

  1. Use const and inline wherever applicable.
  • const: Specifies that the value of a variable cannot be changed.

  • inline: Specifies that a function should be inlined, i.e. its code is substituted at the point of call.

Example:

#include <iostream>

inline int max(int x, int y) {
   return (x > y) ? x : y;
}

int main() {
   std::cout << max(10, 20) << std::endl;
   return 0;
}
  1. Avoid using global variables.
  • Use local variables whenever possible.
  • Use static variables for data that needs to persist across multiple function calls.

Example:

#include <iostream>

void func1() {
   static int count = 0;
   count++;
   std::cout << count << std::endl;
}

int main() {
   func1();
   func1();
   return 0;
}
  1. Use pointers judiciously.
  • Avoid using pointers whenever possible.
  • Use smart pointers to manage dynamically allocated memory.

Example:

#include <iostream>
#include <memory>

int main() {
   std::unique_ptr<int> ptr(new int);
   *ptr = 42;
   std::cout << *ptr << std::endl;
   return 0;
}
  1. Avoid using exceptions.
  • Use exceptions only in exceptional circumstances.
  • Use error codes or return values to report errors.

Example:

#include <iostream>

int divide(int x, int y) {
   if (y == 0) {
      return 0;
   }
   return x / y;
}

int main() {
   int result = divide(10, 2);
   std::cout << result << std::endl;
   return 0;
}
  1. Prefer standard algorithms and data structures.
  • Use the Standard Template Library (STL) to implement common algorithms and data structures.

Example:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
   std::vector<int> vec = {10, 20, 30, 40};
   std::sort(vec.begin(), vec.end());
   for (int i : vec) {
      std::cout << i << std::endl;
   }
   return 0;
}

Most useful resources for learning and improving your C++ skills

  1. The C++ Standard Library – http://www.cplusplus.com/reference/
  2. cppreference.com – https://en.cppreference.com/w/
  3. The C++ Programming Language by Bjarne Stroustrup – https://www.amazon.com/Programming-Language-4th-Bjarne-Stroustrup/dp/0321563840
  4. Effective Modern C++ by Scott Meyers – https://www.amazon.com/Effective-Modern-Specific-Ways-Improve/dp/1491903996
  5. C++ Primer by Lippman, Lajoie, and Moo – https://www.amazon.com/Primer-5th-Stanley-B-Lippman/dp/0321714113
  6. Codecademy’s Learn C++ Course – https://www.codecademy.com/learn/learn-c-plus-plus
  7. Udemy’s C++ course – https://www.udemy.com/topic/c-plus-plus/
  8. C++ Weekly – a weekly video series by Jason Turner – https://www.youtube.com/channel/UCMlGfp2LbKqZzmE5QXKZz5w

These resources will help you learn the basics, understand advanced concepts, and stay up-to-date with the latest C++ features and best practices.

Conclusion

In conclusion, this cheat sheet provides a comprehensive overview of the essential components of the C++ programming language. From basic syntax and data types to classes, objects, and dynamic memory allocation, this cheat sheet covers the key concepts and techniques you need to know to be successful with C++. Whether you are just starting out or you are an experienced programmer looking to expand your skills, this cheat sheet is a valuable resource that can help you write efficient, effective, and high-quality code. So, be sure to keep this cheat sheet handy as you continue your C++ journey and remember to always keep learning and growing your skills.

Tools I use for this site

  • I buy all my domain names on  Namecheap, as thetrendycoder.com
  • The hosting of this website is made on Bluehost.
  • The website is created with WordPress.org (and not WordPress.com).
  • I use the page builder Elementor because it makes it easy to create modern pages with drag and drop.
  • I have multiple websites, and on most of them, I use themes from wpKoi. I love their design, they are very original and work well with Elementor.
  • All the designs and images are created using canvas.
  • I use Grammarly and languagetool to correct all my spelling and grammar mistakes.
  • SEO is a big thing on a website, I use a WordPress plugin called YoastSEO to help me with the basic analysis. I also use a tool called Keysearch for choosing the right keywords.
  • To handle affiliate links, I use two platforms: impact and ShareASale.

You want to write on TheTrendyCoder ?

If you are interested in publishing guest articles on this website, sharing your experience or coding tutorials, apply through this form.

NO EXPERIENCE needed!
NO PERFECT English needed!
NO DEGREE needed!
NO AGE limits!

No matter at what stage we are in our tech journey, we all have learned things and experienced things. Sharing them can help others and even help us. So, if you are a student, a professional, or a self-taught coder, feel at home and share some of your knowledge with the community.

More cheatsheets

The Ultimate iptables Cheat Sheet

/*! elementor - v3.12.1 - 02-04-2023 */ .elementor-heading-title{padding:0;margin:0;line-height:1}.elementor-widget-heading .elementor-heading-title[class*=elementor-size-]>a{color:inherit;font-size:inherit;line-height:inherit}.elementor-widget-heading .elementor-heading-title.elementor-size-small{font-size:15px}.elementor-widget-heading .elementor-heading-title.elementor-size-medium{font-size:19px}.elementor-widget-heading …

Agile cheat sheet for beginners

/*! elementor - v3.12.1 - 02-04-2023 */ .elementor-heading-title{padding:0;margin:0;line-height:1}.elementor-widget-heading .elementor-heading-title[class*=elementor-size-]>a{color:inherit;font-size:inherit;line-height:inherit}.elementor-widget-heading .elementor-heading-title.elementor-size-small{font-size:15px}.elementor-widget-heading .elementor-heading-title.elementor-size-medium{font-size:19px}.elementor-widget-heading …

More resources

coding games

Women in tech

TheTrendyBrand