C++ Cheat Sheet PDF Download

In this blog, I am going to list a complete C++ cheat sheet with PDF to download. You can use this cheat sheet for a quick overview.

But Before that Let’s take a quick introduction to this C++ programming language.

C++ is a high-level programming language that is widely used for developing complex software applications, operating systems, and games.

It is an extension of the C programming language and provides additional features such as object-oriented programming, templates, and exception handling.

Here is a complete cheat sheet with explanations of the most commonly used C++ syntax and concepts:

C++ Cheat Sheet PDF Download

Basic Syntax

Comments

cppCopy code// This is a single line comment.

/* This is a
   multi-line comment. */

Variables

cppCopy code<code>int x = 10;  // integer
float y = 3.14;  // floating-point number
double z = 2.71828;  // double-precision floating-point number
char c = 'a';  // character
bool b = true;  // boolean (true or false)
</code>

Operators

cppCopy code
+  // addition
-  // subtraction
*  // multiplication
/  // division
%  // modulus (remainder)
== // equality
!= // not equal
<  // less than
>  // greater than
<= // less than or equal to
>= // greater than or equal to
&& // logical AND
|| // logical OR
!  // logical NOT

Input/Output

cppCopy code
<code>#include <iostream>

using namespace std;

int main() {
  int x;
  cout << "Enter a number: ";
  cin >> x;
  cout << "You entered: " << x << endl;
  return 0;
}
</code>

Control Structures

Conditional Statements

cppCopy code

<code>if (condition) {
  // code to execute if condition is true
} else {
  // code to execute if condition is false
}

switch (expression) {
  case value1:
    // code to execute if expression equals value1
    break;
  case value2:
    // code to execute if expression equals value2
    break;
  default:
    // code to execute if expression doesn't match any value
}
</code>

Loops

cppCopy code

<code>for (initialization; condition; update) {
  // code to execute repeatedly while condition is true
}

while (condition) {
  // code to execute repeatedly while condition is true
}

do {
  // code to execute at least once, then repeatedly while condition is true
} while (condition);
</code>

Functions

Function Declaration

cppCopy code

<code>return_type function_name(parameter_list) {
  // code to execute
  return return_value;
}
</code>

Function Call

cppCopy code

function_name(argument_list);

Example

cppCopy code
<code>#include <iostream>

using namespace std;

int add(int x, int y) {
  return x + y;
}

int main() {
  int a = 10;
  int b = 20;
  int result = add(a, b);
  cout << "The sum of " << a << " and " << b << " is " << result << endl;
  return 0;
}
</code>

Arrays

cppCopy code

data_type array_name[array_size];

int numbers[5] = {1, 2, 3, 4, 5};

Pointers

cppCopy code

<code>data_type* pointer_name;

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

cout << "The value of x is " << x << endl;  // 10
cout << "The address of x is " << &x << endl;  // some memory address
cout << "The value of p is " << p << endl;  // the address of x
cout << "The value pointed to by p is " << *p << endl
</code>

Classes

Class Declaration

cppCopy code

<code>class class_name {
  private:
    // private data members and functions
  public:
    // public data members and functions
};
</code>

Object Declaration

cppCopy code

class_name object_name;

Constructor

cppCopy code

<code>class class_name {
  public:
    class_name(argument_list) {
      // initialization code
    }
};
</code>

Destructor

cppCopy code

<code>class class_name {   public:     ~class_name() {       // cleanup code     } }; </code>

Example

cppCopy code


<code>#include <iostream>

using namespace std;

class Circle {
  private:
    double radius;
  public:
    Circle(double r) {
      radius = r;
    }
    double getArea() {
      return 3.14159 * radius * radius;
    }
};

int main() {
  Circle c(5.0);
  cout << "The area of the circle is " << c.getArea() << endl;
  return 0;
}
</code>

Inheritance

cppCopy code

<code>class base_class {
  protected:
    // protected data members and functions
};

class derived_class : access_specifier base_class {
  private:
    // private data members and functions
  public:
    // public data members and functions
};
</code>

Example

cppCopy code

<code>#include <iostream>

using namespace std;

class Shape {
  protected:
    double width;
    double height;
  public:
    Shape(double w, double h) {
      width = w;
      height = h;
    }
};

class Rectangle : public Shape {
  public:
    Rectangle(double w, double h) : Shape(w, h) {}
    double getArea() {
      return width * height;
    }
};

int main() {
  Rectangle r(5.0, 10.0);
  cout << "The area of the rectangle is " << r.getArea() << endl;
  return 0;
}
</code>

Templates

cppCopy code

<code>template <typename T>
T max(T a, T b) {
  return a > b ? a : b;
}

int main() {
  int x = 10;
  int y = 20;
  cout << "The maximum of " << x << " and " << y << " is " << max(x, y) << endl;
  return 0;
}
</code>

Exception Handling

cppCopy code

<code>try {
  // code that might throw an exception
} catch (exception_type e) {
  // code to handle the exception
} catch (...) {
  // code to handle all other exceptions
}
</code>

Example

cppCopy code

<code>#include <iostream>

using namespace std;

int main() {
  try {
    int x, y;
    cout << "Enter two numbers: ";
    cin >> x >> y;
    if (y == 0) {
      throw runtime_error("Divide by zero exception");
    }
    double result = x / y;
    cout << "The result is " << result << endl;
  } catch (exception& e) {
    cout << "Exception: " << e.what() << endl;
  }
  return 0;
}
</code>

Sure, I’d be happy to explain each of the concepts and syntax in the cheat sheet in more detail. Here are the explanations:

Comments

Comments are used to add notes to your code that will not be executed by the compiler. They are useful for adding explanations to your code or for temporarily disabling parts of your code. In C++, there are two types of comments: single-line comments and multi-line comments.

Single-line comments start with // and continue until the end of the line. For example:

cppCopy code// This is a single-line comment

Multi-line comments start with /* and end with */. They can span multiple lines. For example:

cppCopy code/*
This is a multi-line comment.
It can span multiple lines.
*/

Data Types

Data types specify the type of data that a variable can hold. In C++, there are several built-in data types, including:

  • int: integers (whole numbers) that can be positive, negative, or zero
  • double: floating-point numbers (decimal numbers)
  • bool: boolean values (true or false)
  • char: single characters
  • string: a sequence of characters

You can also define your own custom data types using classes and structures.

Variables

Variables are used to store data in memory. In C++, you need to declare a variable before you can use it. To declare a variable, you need to specify its data type and a name. For example:

cppCopy codeint age;
double temperature;
bool is_raining;

You can also assign a value to a variable when you declare it. For example:

cppCopy codeint age = 30;
double temperature = 98.6;
bool is_raining = true;

Constants

Constants are values that cannot be changed once they are defined. In C++, you can define a constant using the const keyword. For example:

cppCopy codeconst int MAX_VALUE = 100;
const double PI = 3.14159;

Operators

Operators are symbols or keywords that perform operations on one or more values. In C++, there are several types of operators, including:

  • Arithmetic operators: +, -, *, /, %
  • Comparison operators: ==, !=, <, >, <=, >=
  • Logical operators: &&, ||, !
  • Assignment operators: =, +=, -=, *=, /=, %=

Control Structures

Control structures are used to control the flow of execution in a program. In C++, there are several types of control structures, including:

  • If statement: used to execute a block of code if a condition is true
  • If-else statement: used to execute one block of code if a condition is true and another block of code if it is false
  • Switch statement: used to execute different blocks of code depending on the value of a variable or expression
  • While loop: used to execute a block of code repeatedly as long as a condition is true
  • For loop: used to execute a block of code repeatedly for a specific number of times
  • Do-while loop: used to execute a block of code repeatedly at least once and then as long as a condition is true

Functions

Functions are blocks of code that perform a specific task. In C++, you can define your own functions using the function_name(arguments) syntax. For example:

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

You can then call your function using its name and providing the required arguments. For example:

cppCopy codeint result
cppCopy coderesult = add(2, 3);

Arrays

Arrays are used to store a collection of values of the same data type. In C++, you can define an array using square brackets [] after the variable name. For example:

cppCopy codeint numbers[5];

You can then access individual elements of the array using their index. In C++, array indexes start at 0. For example:

cppCopy codenumbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;

Pointers

Pointers are variables that store memory addresses. They are used to manipulate data in memory directly. In C++, you can define a pointer using the * symbol. For example:

cppCopy codeint *p;

You can then assign a memory address to the pointer using the address-of operator &. For example:

cppCopy codeint x = 10;
p = &x;

You can then access the value at the memory address using the dereference operator *. For example:

cppCopy codeint y = *p;  // y is now equal to 10

Classes

Classes are used to define custom data types. They are made up of data members (variables) and member functions (methods). In C++, you can define a class using the class keyword. For example:

cppCopy codeclass Person {
public:
  string name;
  int age;
  void say_hello() {
    cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl;
  }
};

You can then create objects (instances) of the class using the class name and the object_name.member_name syntax. For example:

cppCopy codePerson john;
john.name = "John";
john.age = 30;
john.say_hello();

This will output: Hello, my name is John and I am 30 years old.

Inheritance

Inheritance is a way to create a new class that is a modified version of an existing class. The new class (called the derived class) inherits the data members and member functions of the existing class (called the base class). In C++, you can define inheritance using the class derived_class : access_specifier base_class syntax. For example:

cppCopy codeclass Student : public Person {
public:
  string major;
  void say_major() {
    cout << "My major is " << major << "." << endl;
  }
};

This defines a new Student class that inherits from the Person class. The Student class adds a new data member major and a new member function say_major(). You can then create objects of the Student class that can also access the data members and member functions of the Person class. For example:

cppCopy codeStudent jane;
jane.name = "Jane";
jane.age = 20;
jane.major = "Computer Science";
jane.say_hello();
jane.say_major();

This will output:

pythonCopy codeHello, my name is Jane and I am 20 years old.
My major is Computer Science.

Templates

Templates are used to create functions or classes that can work with multiple data types. In C++, you can define a template using the template keyword followed by the template parameter(s) in angle brackets <>. For example:

cppCopy codetemplate <typename T>
T add(T a, T b) {
  return a + b;
}

This defines a template function called add() that can work with any data type T. You can then call this function with different data types, and the compiler will generate the appropriate function for each type. For example:

cppCopy codeint result1 = add(2, 3);          // result1 is 5
double result2 = add(2.5, 3.5);   // result2 is 6.0

Exceptions

Exceptions are used to handle errors and unexpected situations in your code. In C++, you can throw an exception using the throw keyword, and catch an exception using the try-catch block. For example:

cppCopy codetry {
  int x = 10;
  int y = 0;
  if (y == 0) {
    throw "Division by zero!";
  }
  int result = x / y;
  cout << "Result: " << result << endl;
} catch (const char* msg) {
  cerr << "Error: " << msg << endl;
}

This code attempts to divide x by y, but throws an exception if y is 0. The exception message is a string literal "Division by zero!". The try-catch block catches this exception and prints an error message to the console.

Smart Pointers

Smart pointers are used to manage memory allocation and deallocation in your code. They automatically delete objects when they are no longer needed, which helps to avoid memory leaks and dangling pointers. In C++, there are two types of smart pointers: unique_ptr and shared_ptr.

A unique_ptr is used to manage a single object that has no other owners. It automatically deletes the object when the unique_ptr is destroyed or reset. For example:

cppCopy codeunique_ptr<int> p(new int(10));

This creates a unique_ptr that manages an integer with value 10. When the unique_ptr goes out of scope, the integer is automatically deleted.

A shared_ptr is used to manage an object that has multiple owners. It keeps track of how many owners there are, and deletes the object when there are no more owners. For example:

cppCopy codeshared_ptr<int> p1(new int(10));
shared_ptr<int> p2 = p1;

This creates two shared_ptrs that both manage the same integer with value 10. When p1 and p2 go out of scope, the integer is automatically deleted because there are no more owners.

Standard Template Library (STL)

The Standard Template Library (STL) is a collection of C++ templates that provide useful data structures and algorithms. It includes containers like vectors, sets, and maps, as well as algorithms like sorting, searching, and transforming. You can use the STL by including the appropriate header files and using the templates in your code. For example:

cppCopy code#include <vector>
#include <algorithm>

vector<int> nums = {5, 2, 8, 1, 9};
sort(nums.begin(), nums.end());
for (int n : nums) {
  cout << n << " ";
}

This code creates a vector of integers nums, sorts it using the sort() algorithm from the <algorithm> header, and then prints each element to the console. The output will be: 1 2 5 8 9.

Namespaces

Namespaces are used to organize code into logical groups and avoid naming conflicts. You can define a namespace using the namespace keyword, and then access the contents of the namespace using the scope resolution operator ::. For example:

cppCopy codenamespace mynamespace {
  int x = 10;
  void foo() {
    cout << "Hello from mynamespace!" << endl;
  }
}

int main() {
  cout << mynamespace::x << endl;
  mynamespace::foo();
  return 0;
}

This code defines a namespace called mynamespace that contains an integer variable x and a function foo(). In the main() function, we access x and foo() using the scope resolution operator. The output will be:

pythonCopy code10
Hello from mynamespace!

Friend Functions

Friend functions are functions that have access to the private and protected members of a class. You can declare a function as a friend of a class using the friend keyword. For example:

cppCopy codeclass MyClass {
private:
  int x;
public:
  MyClass(int a) : x(a) {}
  friend void printX(MyClass obj);
};

void printX(MyClass obj) {
  cout << obj.x << endl;
}

int main() {
  MyClass obj(10);
  printX(obj);
  return 0;
}

This code defines a class MyClass with a private member x, and a friend function printX() that can access x. In the main() function, we create an object of MyClass and call printX() to print its private member x to the console. The output will be: 10.

Virtual Functions

Virtual functions are functions that can be overridden in a derived class. They are used to implement polymorphism, which allows you to use objects of different derived classes in the same way as objects of the base class. You can define a virtual function using the virtual keyword in the base class, and override it in the derived class using the override keyword. For example:

cppCopy codeclass Animal {
public:
  virtual void makeSound() {
    cout << "The animal makes a sound." << endl;
  }
};

class Dog : public Animal {
public:
  void makeSound() override {
    cout << "The dog barks." << endl;
  }
};

int main() {
  Animal* animal1 = new Animal();
  Animal* animal2 = new Dog();
  animal1->makeSound();
  animal2->makeSound();
  return 0;
}

This code defines a base class Animal with a virtual function makeSound(), and a derived class Dog that overrides makeSound(). In the main() function, we create objects of both classes and call makeSound() on them. The output will be:

cssCopy codeThe animal makes a sound.
The dog barks.

Even though animal2 is declared as an Animal* pointer, it still calls the overridden makeSound() function in the Dog class because it is a virtual function.

Templates

Templates are used to define generic classes and functions that can work with different data types. You can define a template using the template keyword, followed by a list of template parameters enclosed in angle brackets. For example:

cppCopy codetemplate<typename T>
class MyClass {
private:
  T x;
public

List c++ all important inbuilt functions with explanation

Here are some important built-in functions in C++ with explanations:

Input/Output Functions

  • cin – reads input from the console
  • cout – prints output to the console
  • getline() – reads a line of input from the console and stores it in a string
  • printf() – prints formatted output to the console, similar to the C function

String Functions

  • strlen() – returns the length of a string
  • strcpy() – copies one string to another
  • strcat() – concatenates one string to another
  • strcmp() – compares two strings lexicographically
  • toupper() – converts a character to uppercase
  • tolower() – converts a character to lowercase

Mathematical Functions

  • sqrt() – returns the square root of a number
  • pow() – raises a number to a power
  • abs() – returns the absolute value of a number
  • floor() – rounds a number down to the nearest integer
  • ceil() – rounds a number up to the nearest integer
  • round() – rounds a number to the nearest integer

Array Functions

  • sizeof() – returns the size of an array in bytes
  • memset() – sets a block of memory to a given value
  • memcpy() – copies a block of memory from one location to another

STL Functions

The Standard Template Library (STL) is a collection of built-in C++ classes and functions for various purposes. Here are some important STL functions:

  • vector<T> – a dynamic array class that can hold objects of type T
  • list<T> – a linked list class that can hold objects of type T
  • map<K, V> – an associative array class that maps keys of type K to values of type V
  • set<T> – a class that represents a set of unique elements of type T
  • algorithm – a header file that contains many useful functions for manipulating STL containers, such as sort(), find(), and reverse()

These are just a few examples of the many built-in functions available in C++.

write this with simple programming examples

Sure, here are some simple programming examples of the built-in functions I mentioned:

Input/Output Functions

cppCopy code#include <iostream>
#include <string>
using namespace std;

int main() {
  int age;
  string name;

  cout << "Enter your name: ";
  cin >> name;
  cout << "Enter your age: ";
  cin >> age;

  cout << "Hello, " << name << ". You are " << age << " years old." << endl;

  return 0;
}

String Functions

cppCopy code#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

int main() {
  char str1[10] = "hello";
  char str2[10] = "world";
  char str3[20];

  // strlen()
  cout << "Length of str1: " << strlen(str1) << endl;

  // strcpy()
  strcpy(str3, str1);
  cout << "str3 after strcpy(str3, str1): " << str3 << endl;

  // strcat()
  strcat(str3, str2);
  cout << "str3 after strcat(str3, str2): " << str3 << endl;

  // strcmp()
  if (strcmp(str1, str2) < 0) {
    cout << "str1 is less than str2" << endl;
  } else {
    cout << "str1 is greater than or equal to str2" << endl;
  }

  // toupper()
  cout << "Uppercase of 'a': " << toupper('a') << endl;

  // tolower()
  cout << "Lowercase of 'A': " << tolower('A') << endl;

  return 0;
}

Mathematical Functions

cppCopy code#include <iostream>
#include <cmath>
using namespace std;

int main() {
  double x = 4.0;

  // sqrt()
  cout << "Square root of " << x << ": " << sqrt(x) << endl;

  // pow()
  cout << "2 raised to the power of 3: " << pow(2, 3) << endl;

  // abs()
  cout << "Absolute value of -7: " << abs(-7) << endl;

  // floor()
  cout << "Floor of 5.7: " << floor(5.7) << endl;

  // ceil()
  cout << "Ceil of 5.1: " << ceil(5.1) << endl;

  // round()
  cout << "Round of 4.5: " << round(4.5) << endl;

  return 0;
}

Array Functions

cppCopy code#include <iostream>
#include <cstring>
using namespace std;

int main() {
  int arr[5] = {1, 2, 3, 4, 5};

  // sizeof()
  cout << "Size of arr: " << sizeof(arr) << " bytes" << endl;

  // memset()
  memset(arr, 0, sizeof(arr));
  cout << "arr after memset(arr, 0, sizeof(arr)): ";
  for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;

  int arr2[5] = {6, 7, 8, 9, 10};

  // memcpy()
  memcpy(arr, arr2, sizeof(arr));
  cout << "arr after memcpy(arr, arr2, sizeof(arr)): ";
  for (int i = 0; i < 5; i

continue

cppCopy code    cout << arr[i] << " ";
  }
  cout << endl;

  return 0;
}

Time Functions

cppCopy code#include <iostream>
#include <ctime>
using namespace std;

int main() {
  // time()
  time_t now = time(0);
  cout << "Current time: " << ctime(&now);

  // localtime()
  tm *ltm = localtime(&now);
  cout << "Year: " << 1900 + ltm->tm_year << endl;
  cout << "Month: " << 1 + ltm->tm_mon << endl;
  cout << "Day: " << ltm->tm_mday << endl;
  cout << "Hour: " << ltm->tm_hour << endl;
  cout << "Minute: " << ltm->tm_min << endl;
  cout << "Second: " << ltm->tm_sec << endl;

  return 0;
}

Type Conversion Functions

cppCopy code#include <iostream>
#include <string>
using namespace std;

int main() {
  int num = 5;
  double dbl = 3.14159;

  // to_string()
  string str_num = to_string(num);
  cout << "str_num: " << str_num << endl;

  // stoi()
  string str_int = "42";
  int int_num = stoi(str_int);
  cout << "int_num: " << int_num << endl;

  // stod()
  string str_dbl = "2.71828";
  double dbl_num = stod(str_dbl);
  cout << "dbl_num: " << dbl_num << endl;

  // static_cast()
  int x = 10;
  double y = static_cast<double>(x);
  cout << "y: " << y << endl;

  return 0;
}

list all C++ reserve keywords with explanation

Here is a list of all C++ reserved keywords along with a brief explanation:

  • alignas: specifies a preferred alignment for a variable or type
  • alignof: determines the alignment requirement of a type
  • and: logical AND operator
  • and_eq: performs a bitwise AND and assignment operation
  • asm: allows inline assembly language code in C++ program
  • auto: specifies automatic storage duration and type deduction
  • bitand: performs a bitwise AND operation
  • bitor: performs a bitwise OR operation
  • bool: boolean data type that represents true or false values
  • break: breaks out of a loop or switch statement
  • case: defines a case label in a switch statement
  • catch: catches and handles exceptions in a try-catch block
  • char: character data type that represents a single character
  • char16_t: character data type that represents a 16-bit Unicode character
  • char32_t: character data type that represents a 32-bit Unicode character
  • class: defines a class type in C++
  • compl: performs a bitwise NOT operation
  • const: specifies that a variable’s value cannot be changed
  • constexpr: specifies that a variable or function is a constant expression
  • const_cast: converts a const or volatile type to a non-const or non-volatile type
  • continue: skips the current iteration of a loop
  • decltype: determines the type of an expression
  • default: specifies the default case in a switch statement
  • delete: deletes a dynamically allocated object or function
  • do: initiates a do-while loop
  • double: floating-point data type that represents real numbers
  • dynamic_cast: converts a polymorphic type to another type
  • else: specifies an alternative branch in an if statement
  • enum: defines an enumeration type in C++
  • explicit: specifies that a constructor is not used for implicit type conversions
  • export: specifies that a variable or function is accessible outside the current translation unit
  • extern: specifies that a variable or function is defined in another translation unit
  • false: boolean literal that represents a false value
  • float: floating-point data type that represents real numbers with less precision than double
  • for: initiates a for loop
  • friend: grants access to private or protected members of a class to a non-member function or class
  • goto: transfers control to a labeled statement in a function
  • if: initiates an if statement
  • inline: specifies that a function should be inlined at the call site
  • int: integer data type that represents whole numbers
  • long: integer data type that represents whole numbers with a larger range than int
  • mutable: specifies that a member variable can be modified even in a const object or function
  • namespace: defines a namespace to organize program elements
  • new: allocates memory for a dynamic object or array
  • noexcept: specifies that a function does not throw an exception
  • not: logical NOT operator
  • not_eq: performs a bitwise NOT and assignment operation
  • nullptr: null pointer literal
  • operator: defines an operator function
  • or: logical OR operator
  • or_eq: performs a bitwise OR and assignment operation
  • private: specifies private access level for class members
  • protected: specifies protected access level for class members
  • public: specifies public access level for class members
  • register: specifies a variable that is stored in a register instead of memory
  • reinterpret_cast: converts a pointer to

continue

a different type of pointer without changing its value

  • return: returns a value from a function
  • short: integer data type that represents whole numbers with a smaller range than int
  • signed: specifies a signed integer data type
  • sizeof: determines the size of a type or variable in bytes
  • static: specifies that a variable or function has static storage duration and is only accessible in its translation unit
  • static_assert: checks a compile-time assertion
  • static_cast: converts a type to another type
  • struct: defines a struct type in C++
  • switch: initiates a switch statement
  • template: defines a template for a class or function
  • this: pointer to the current object in a member function of a class
  • thread_local: specifies that a variable has thread-local storage duration
  • throw: throws an exception in a function
  • true: boolean literal that represents a true value
  • try: initiates a try-catch block to handle exceptions
  • typedef: defines a type alias for an existing type
  • typeid: determines the type of an object
  • typename: specifies a dependent type in a template declaration
  • union: defines a union type in C++
  • unsigned: specifies an unsigned integer data type
  • using: introduces a name into the current scope
  • virtual: specifies a virtual function or method in a class
  • void: specifies that a function has no return value or that a pointer points to no type
  • volatile: specifies that a variable’s value can be changed by hardware or other processes outside the program’s control
  • wchar_t: wide character data type that represents a single wide character
  • while: initiates a while loop

These keywords have special meanings in C++ and cannot be used as variable or function names.

Leave a Comment