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 zerodouble
: floating-point numbers (decimal numbers)bool
: boolean values (true
orfalse
)char
: single charactersstring
: 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_ptr
s 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 consolecout
– prints output to the consolegetline()
– reads a line of input from the console and stores it in a stringprintf()
– prints formatted output to the console, similar to the C function
String Functions
strlen()
– returns the length of a stringstrcpy()
– copies one string to anotherstrcat()
– concatenates one string to anotherstrcmp()
– compares two strings lexicographicallytoupper()
– converts a character to uppercasetolower()
– converts a character to lowercase
Mathematical Functions
sqrt()
– returns the square root of a numberpow()
– raises a number to a powerabs()
– returns the absolute value of a numberfloor()
– rounds a number down to the nearest integerceil()
– rounds a number up to the nearest integerround()
– rounds a number to the nearest integer
Array Functions
sizeof()
– returns the size of an array in bytesmemset()
– sets a block of memory to a given valuememcpy()
– 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 Tlist<T>
– a linked list class that can hold objects of type Tmap<K, V>
– an associative array class that maps keys of type K to values of type Vset<T>
– a class that represents a set of unique elements of type Talgorithm
– a header file that contains many useful functions for manipulating STL containers, such assort()
,find()
, andreverse()
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 typealignof
: determines the alignment requirement of a typeand
: logical AND operatorand_eq
: performs a bitwise AND and assignment operationasm
: allows inline assembly language code in C++ programauto
: specifies automatic storage duration and type deductionbitand
: performs a bitwise AND operationbitor
: performs a bitwise OR operationbool
: boolean data type that represents true or false valuesbreak
: breaks out of a loop or switch statementcase
: defines a case label in a switch statementcatch
: catches and handles exceptions in a try-catch blockchar
: character data type that represents a single characterchar16_t
: character data type that represents a 16-bit Unicode characterchar32_t
: character data type that represents a 32-bit Unicode characterclass
: defines a class type in C++compl
: performs a bitwise NOT operationconst
: specifies that a variable’s value cannot be changedconstexpr
: specifies that a variable or function is a constant expressionconst_cast
: converts a const or volatile type to a non-const or non-volatile typecontinue
: skips the current iteration of a loopdecltype
: determines the type of an expressiondefault
: specifies the default case in a switch statementdelete
: deletes a dynamically allocated object or functiondo
: initiates a do-while loopdouble
: floating-point data type that represents real numbersdynamic_cast
: converts a polymorphic type to another typeelse
: specifies an alternative branch in an if statementenum
: defines an enumeration type in C++explicit
: specifies that a constructor is not used for implicit type conversionsexport
: specifies that a variable or function is accessible outside the current translation unitextern
: specifies that a variable or function is defined in another translation unitfalse
: boolean literal that represents a false valuefloat
: floating-point data type that represents real numbers with less precision than doublefor
: initiates a for loopfriend
: grants access to private or protected members of a class to a non-member function or classgoto
: transfers control to a labeled statement in a functionif
: initiates an if statementinline
: specifies that a function should be inlined at the call siteint
: integer data type that represents whole numberslong
: integer data type that represents whole numbers with a larger range than intmutable
: specifies that a member variable can be modified even in a const object or functionnamespace
: defines a namespace to organize program elementsnew
: allocates memory for a dynamic object or arraynoexcept
: specifies that a function does not throw an exceptionnot
: logical NOT operatornot_eq
: performs a bitwise NOT and assignment operationnullptr
: null pointer literaloperator
: defines an operator functionor
: logical OR operatoror_eq
: performs a bitwise OR and assignment operationprivate
: specifies private access level for class membersprotected
: specifies protected access level for class memberspublic
: specifies public access level for class membersregister
: specifies a variable that is stored in a register instead of memoryreinterpret_cast
: converts a pointer to
continue
a different type of pointer without changing its value
return
: returns a value from a functionshort
: integer data type that represents whole numbers with a smaller range than intsigned
: specifies a signed integer data typesizeof
: determines the size of a type or variable in bytesstatic
: specifies that a variable or function has static storage duration and is only accessible in its translation unitstatic_assert
: checks a compile-time assertionstatic_cast
: converts a type to another typestruct
: defines a struct type in C++switch
: initiates a switch statementtemplate
: defines a template for a class or functionthis
: pointer to the current object in a member function of a classthread_local
: specifies that a variable has thread-local storage durationthrow
: throws an exception in a functiontrue
: boolean literal that represents a true valuetry
: initiates a try-catch block to handle exceptionstypedef
: defines a type alias for an existing typetypeid
: determines the type of an objecttypename
: specifies a dependent type in a template declarationunion
: defines a union type in C++unsigned
: specifies an unsigned integer data typeusing
: introduces a name into the current scopevirtual
: specifies a virtual function or method in a classvoid
: specifies that a function has no return value or that a pointer points to no typevolatile
: specifies that a variable’s value can be changed by hardware or other processes outside the program’s controlwchar_t
: wide character data type that represents a single wide characterwhile
: initiates a while loop
These keywords have special meanings in C++ and cannot be used as variable or function names.