C++ Cheatsheet

Basics

Basic syntax and functions from the C++ programming language.

#include <iostream>
using namespace std;
int main() {
cout <<"Hello World";
return 0;
}

It prints output on the screen

cout << "This is C++ Programming";

It takes input from the user

cin >> variable_name

Data types

The data type is the type of data

Typically a single octet(one byte). It is an integer type

char variable_name;

The most natural size of integer for the machine

int variable_name;

A single-precision floating-point value

float variable_name;

A double-precision floating-point value

double variable_name;

Represents the absence of the type

void
bool

Escape Sequences

It is a sequence of characters starting with a backslash, and it doesn't represent itself when used inside string literal.

\a
\b
\f
\n
\r
\t
\\
\'
\?
\nnn
\xhh
\0

Comments

A comment is a code that is not executed by the compiler, and the programmer uses it to keep track of the code.

// It's a single line comment
/* It's a 
multi-line
comment
*/

Strings

It is a collection of characters surrounded by double quotes

#include <string>
string variable1 = "Hello World";
string fullName = firstName.append(lastName);
cout << fullName;
cout << "The length of the string is: " << variable1.length();
string variable1 = "Hello World";
variable1[1] = 'i';
cout << variable1;

Maths

C++ provides some built-in math functions that help the programmer to perform mathematical operations efficiently.

cout << max(25, 140);
cout << min(55, 50);
#include <cmath>
cout << sqrt(144);
ceil(x)
floor(x)
pow(x, y)

Decision Making Instructions

Conditional statements are used to perform operations based on some condition.

if (condition) {
// This block of code will get executed if the condition is True
}
if (condition) {
// If condition is True then this block will get executed
} else {
// If condition is False then this block will get executed
}
if (condition) {
// Statements;
}
else if (condition){
// Statements;
}
else{
// Statements
}
variable = (condition) ? expressionTrue : expressionFalse;
switch (expression)
{
case constant-expression:
statement1;
statement2;
break;
case constant-expression:
statement;
break;
...
default:
statement;
}

Iterative Statements

Iterative statements facilitate programmers to execute any block of code lines repeatedly and can be controlled as per conditions added by the programmer.

while (/* condition */)
{
/* code block to be executed */
}
do
{
/* code */
} while (/* condition */);
for (int i = 0; i < count; i++)
{
/* code */
}
break;
continue;

References

Reference is an alias for an already existing variable. Once it is initialized to a variable, it cannot be changed to refer to another variable. So, it's a const pointer.

Creating References

string var1 = "Value1"; // var1 variable
string &var2 = var1; // reference to var1

Pointers

Pointer is a variable that holds the memory address of another variable

Declaration

datatype *var_name;
var_name = &variable2;

Functions & Recursion

Functions are used to divide an extensive program into smaller pieces. It can be called multiple times to provide reusability and modularity to the C program.

return_type function_name(data_type parameter...){
//code to be executed 
}
function_name(arguments);

Recursion is when a function calls a copy of itself to work on a minor problem. And the function that calls itself is known as the Recursive function.

void recurse()
{
... .. ...
recurse();
... .. ...
}

Object-Oriented Programming

It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world entity.

class
class Class_name {
public: // Access specifier
// fields
// functions
// blocks
};
object
Class_name ObjectName;

Constructors

It is a special method that is called automatically as soon as the object is created.

class className { // The class
public: // Access specifier
className() { // Constructor
}
};
int main() {
className obj_name;
return 0;
}

Encapsulation

Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

#include<iostream>
using namespace std;
class ExampleEncap{
private:
/* Since we have marked these data members private, 
* any entity outside this class cannot access these 
* data members directly, they have to use getter and 
* setter functions. 
*/
int num;
char ch;
public:
/* Getter functions to get the value of data members. 
* Since these functions are public, they can be accessed 
* outside the class, thus provide the access to data members 
* through them 
*/
int getNum() const {
return num;
}
char getCh() const {
return ch;
cout << "Harry Potter";
}
/* Setter functions, they are called for assigning the values 
* to the private data members. 
*/
void setNum(int num) {
this->num = num;
}
void setCh(char ch) {
this->ch = ch;
}
};
int main(){
ExampleEncap obj;
obj.setNum(100);
obj.setCh('A');
cout<<obj.getNum()<<endl;
cout<<obj.getCh()<<endl;
return 0;
}

File Handling

File handling refers to reading or writing data from files. C provides some functions that allow us to manipulate data in the files.

#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "File Handling in C++";
// Close the file
MyFile.close();
}

It allows us to read the file line by line

getline()

It opens a file in the C++ program

void open(const char* file_name,ios::openmode mode);

OPEN MODES

fs.open ("test.txt", std::fstream::in)
fs.open ("test.txt", std::fstream::out)
fs.open ("test.txt", std::fstream::binary)
fs.open ("test.txt", std::fstream::app)
fs.open ("test.txt", std::fstream::ate)
fs.open ("test.txt", std::fstream::trunc)
fs.open ("test.txt", std::fstream::nocreate)
fs.open ("test.txt", std::fstream::noreplace)
myfile.close()

Exception Handling

An exception is an unusual condition that results in an interruption in the flow of the program.

A basic try-catch block in python. When the try block throws an error, the control goes to the except for block

try {
// code to try
throw exception; // If a problem arises, then throw an exception
}
catch () {
// Block of code to handle errors
}

← Back to all posts

Built by Abhiraj with ♥.