C++ Cheat Sheet

C++ Cheat Sheet

C++ Introduction

C++ is a powerful, high-performance programming language used primarily for building operating systems, embedded system software, and video game engines.

Since C++ is quite a harsh language to learn, a cheatsheet can be a valuable resource for both beginners and experienced programmers.

Hello World Program in C++

#include <iostream>
using namespace std;

int main() {
   cout << "Hello World";
   return 0;
}

Here,

  • the directive #include that tells the C++ preprocessor to include a file, which is also known as a header file.
  • namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc.) inside it.
  • iostream is a standard library header file that uses the std namespace.
  • But the main() function indicates the start of a program in C++.

You can use our online C++ compiler to execute C++ code like the one above.


Input/Output

To perform input and output operations in C++, you can use the cin and cout objects, respectively.

Example

#include <iostream>
using namespace std;

int main()
{
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "Your age is: " << age << endl;
    return 0;
}

Comments

In C++, any text after a double slash // is considered a comment.

C++ compiler with ignore the comments but they can help you explain your code. So, commenting on your code is a good coding practice while working on a team.

Here's an example that shows comments in C++:

#include <iostream>
using namespace std;

int main()
{
    float total = 79.5; //initialize a second variable
    cout << "Your total is: " << total;  //print the variable
 }

// Output: Your total is 79.5

Data Types

C++ has three main primitive data types you can use:

1. Integer (int): represents positive or negative whole numbers, such as 12, -6, 0, and 100.

#include <iostream>

int main() {
    // Write C++ code here
    std::cout << -6;

    return 0;
}


//Output: -6

2. Floating point (float): represents real numbers, such as 3.14, -32.6, and 0.0.

#include <iostream>

int main() {
    // Write C++ code here
    std::cout << 12.4;

    return 0;
}

//Output: 12.4

3. String (str): represents a sequence of characters, such as 'Hello World' or "How are you?".

#include <iostream>

int main() {
    // Write C++ code here
    std::cout << "How are you?";

    return 0;
}


//Output: How are you?

Variables

In C++, variables are used to store data values.

We need to declare the data type of a variable in C++.

// declare a variable with an integer value
int age = 25

// declare a variable with a float value
float salary = 52978.84

// declare a variable with a string value
 char name = "Smith"

Here are a few rules of naming a variable in C++

  • Use meaningful names that reflect the purpose of the variable.
  • Begin the name with a lowercase letter, and capitalize subsequent words (camelCase).
  • Avoid using reserved words as variable names.
  • Avoid abbreviations unless they are commonly used.
  • Do not use spaces or special characters (except underscores).
  • Keep the length of the variable name short.

Operators

C++ has support for four main types of operators:

  • Arithmetic Operators: To perform arithmetic operations like addition, subtraction, multiplication, and division.
  • Comparison Operators: To compare values and return a boolean result.
  • Logical Operators: To perform logical operations like and, or, and not.
  • Assignment Operators: To assign values to variables.

Arithmetic operators

C++ supports the following arithmetic operators:

+ (addition): adds two values or variables

#include <iostream>

int main() {
    int a =32;
    int b = 18;
    std::cout << a+b;
    return 0;
}
// Output: 50

- (subtraction): subtracts two values or variables

#include <iostream>

int main() {
    int a =32;
    int b = 18;
    std::cout << a-b;
    return 0;
}

// Output: 14

* (multiplication): multiple two values or variables

#include <iostream>

int main() {
    int a =30;
    int b = 20;
    std::cout << a*b;
    return 0;
}// Output: 600

/ (division): divides two numbers and returns a floating point result

#include <iostream>

int main() {
    int a =30;
    int b = 20;
    std::cout << a/b;
    return 0;
} // Output: 15

% (remainder): returns the remainder of the division of two values or variables

#include <iostream>

int main() {
    int a =130;
    int b = 12;
    std::cout << a%b;
    return 0;
} // Output: 1

Operator Precedence

The arithmetic operators have a defined order of precedence, that specifies which operator will be executed first if there exist multiple operators in a single expression. For example,

result = 5 * 6 + 10 / 5

Here, / is executed first, followed by * and then +

Order of operator precedence from highest to lowest:

  • **
  • *, /, //
  • +, -

You can use parentheses to change the order of precedence and specify which operations should be performed first.

#include <iostream>

int main() {
    int result = 5*6+10/5;
    std::cout <<result;
    return 0;
} // Output: 32

// Output: 32
//  / will be executed first, followed by + and then *

Assignment Operators

C++ supports the following assignment operators:

= (assignment): assign a value to a variable

age = 25
name = 'Smith'

+= (addition assignment): adds the right operand to the left operand and assigns the result to the left operand

number = 12

// equivalent to number = number + 8
number += 8

-= (subtraction assignment): subtracts the right operand from the left operand and assigns the result to the left operand

number = 12

 //equivalent to number = number - 8
number -= 8

*= (multiplication assignment): multiplies the left operand by the right operand and assigns the result to the left operand

number = 12

// equivalent to number = number * 8
number *= 8

/= (division assignment): divides the left operand by the right operand and assigns the result to the left operand

number = 12

// equivalent to number = number / 8
number /= 8

//= (floor division assignment): divides the left operand by the right operand and assigns the integer floor result to the left operand

number = 12

 // equivalent to number = number // 8
number //= 8

%= (remainder assignment): divides the left operand by the right operand and assigns the remainder after division to the left operand

number = 12

 // equivalent to number = number % 8
number %= 8

Comparison Operators

C++ supports the following comparison operators:

== (equal to): checks if two values or variables are equal

a = 20
b = 30

!= (not equal to): checks if two values or variables are not equal

a = 20
b = 30

< (less than): checks if the value on the left is less than the value on the right

a = 20
b = 30

a < b   // Output: True

<= (less than or equal to): checks if the value on the left is less than or equal to the value on the right

a = 20
b = 30

a <= b    // Output: True

> (greater than): checks if the value on the left is greater than the value on the right

a = 20
b = 30

a > b   // Output: False

>= (greater than or equal to): checks if the value on the left is greater than the value on the right

a = 20
b = 30

a >= b    // Output: False

Logical Operators

C++ supports the following logical operators:

and (Logical AND): returns True if both operands are True, else returns False

a = 30
b = 20
c = 10

result = (a > b) and (a > c)

result = (a > b) and (a < c)

Here,

  • (a > b) and (a > c) returns True because both expressions are True.
  • (a > b) and ( a < c) returns False because a < c is False.

or (Logical OR): returns True if at least one operand is True, else returns False

a = 30
b = 20
c = 10

result = (a < b) or (a < c)

result = (a > b) or (a < c)

Here,

  • (a < b) or (a < c) returns False because both expressions are False.
  • (a > b) or (a < c) returns True because a > b is True.

not (Logical NOT): returns True if the operand is False, False if the operand is True

a = 30
b = 20

result = not (a < b)

result = not (a > b)

Here,

  • not (a < b) returns True because a < b is False.
  • not (a > b) returns False because a > b is True.

Conditional Statements

These statements allow you to execute a code block only if a specific condition is met.

Different types of conditional statements available in C++ are:

  • if
  • if...else
  • else...if
  • switch

if statement

The most common conditional statement in C++ is the if statement, which has the following syntax:

if (condition){
    // Code to be executed if the condition is true
}

Example

#include <iostream>

int main() {
  int x = 10;
  int y = 20;

  if (x < y) {
    std::cout << "x is less than y" << std::endl;
  }

  return 0;
}

if-else statement

You can also use the else clause to specify a block of code that should be executed if the condition is false:

if (condition){
    // Code to be executed if the condition is true
}
else{
    // Code to be executed if the condition is false
}

The if-else statement allows you to specify two blocks of code to be executed depending on the value of a condition.

Example

#include <iostream>
using namespace std;

int main() {
    int x = 10;
    if (x > 0) {
    cout << "x is positive" << endl;
    }
    else {
    cout << "x is not positive" << endl;
    }
    return 0;
}

else-if

You can also use the else if clause to specify additional conditions to be tested.

#include <iostream>
using namespace std;

int main() {
    int x = 10;
    if (x > 0){
    cout << "x is positive" << endl;
        
    }
    else if (x < 0){
    cout << "x is negative" << endl;
        
    }
    else{
    cout << "x is zero" << endl;
        
    }
}

Switch Statement

The switch statement allows you to execute a block of code based on the value of a variable or expression.

Example

#include <iostream>
using namespace std;
int main() {
   char grade = 'A';

switch (grade){
    case 'A':
        cout << "Excellent!" << endl;
        break;
    case 'B':
        cout << "Good job!" << endl;
        break;
    case 'C':
        cout << "Average performance" << endl;
        break;
    default:
        cout << "Invalid grade" << endl;
     }
}

Loops

Loops allow you to execute a block of code multiple times.

Types of Loops:

  • for Loop
  • while Loop

for Loop

The for loop is used to execute a block of code a specified number of times.

Example

#include <iostream>
using namespace std;

int main() {
   for (int i = 0; i < 10; i++){
    cout << i << endl;
      }
    }

while Loop

The while loop executes a code block while a particular condition is true.

Example

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  while (i < 10){
    cout << i << endl;
    i++;
  }
}

Functions

Functions allow us to divide related code into small chunks and re-use it as per out needs.

1. Declare Function

In C++, you can declare a function using the following syntax:

return_type function_name(parameter_list) {
    // function body
}

For example, the following is a function that takes two integers as arguments and returns their sum:

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

2. Calling a function

To call a function in C++, you simply use the function name followed by a list of arguments in parentheses. The arguments must match the types and order of the parameters in the function declaration.

To call the sum function defined above, you can do:

int result = sum(2, 3); // result will be 5

Example

#include <iostream>

// function declaration
int sum(int a, int b);

int main() {
    // call the function
    int result = sum(2, 3);
    std::cout << "The sum is: " << result << std::endl;
    return 0;
}

// function definition
int sum(int a, int b) {
    return a + b;
}

In the above C++ program, sum() is a function that returns the sum of two two integer arguments - a and b.

In the main() function, the result of the function is stored in the variable result. Finally, the result is printed.

The program will output "The sum is: 5" to the console.


Object-oriented Programming in C++

Object-oriented programming is a programming paradigm that uses objects, which can contain data and code, to represent real-world entities.

OOP in C++ supports features like classes, objects, constructors, destructors, inheritance, polymorphism, and encapsulation.


Classes

A class is a blueprint for an object. It defines the data that an object of that class will contain, as well as the functions that can be called on that object.

Here is the syntax for defining a class:

class ClassName {
    // data members (variables)
    data_type variable_name;
    ...
    
    // member functions (methods)
    return_type function_name(parameters) {
        // function body
    }
    ...
};

Objects

An object is an instance of a class for manipulating data. Here is the syntax for defining an object:

ClassName object_name;

To access an object's data members and member functions, you can use the dot operator (.).

object_name.data_member;  // access data member
object_name.function_name(parameters);  // call member function

Example

#include <iostream>

class Circle {
public:
  double radius;

  double getArea() {
    return 3.14 * radius * radius;
  }
};

int main() {
  Circle c1;
  c1.radius = 5.0;

  Circle c2;
  c2.radius = 10.0;

  std::cout << "Area of Circle 1: " << c1.getArea() << std::endl;
  std::cout << "Area of Circle 2: " << c2.getArea() << std::endl;

  return 0;
}

Constructors and Destructors

A constructor is a special member function that is called when an object is created. It is used to initialize the object's data members.

A destructor is a special member function that is called when an object is destroyed (e.g., when it goes out of scope). It is used to free up any resources that the object was using.

Here is the syntax for defining a constructor and a destructor:

class ClassName {
    ...
    // constructor
    ClassName(parameters) {
        // constructor body
    }
    ...
    // destructor
    ~ClassName() {
        // destructor body
    }
    ...
};

Example

#include <iostream>

class Rectangle {
public:
  int length;
  int width;

  Rectangle(int l, int w) {
    length = l;
    width = w;
    std::cout << "Rectangle created with length " << length << " and width " << width << std::endl;
  }

  ~Rectangle() {
    std::cout << "Rectangle destroyed with length " << length << " and width " << width << std::endl;
  }
};

int main() {
  Rectangle r1(5, 10);
  return 0;
}

Access Modifiers

Access Modifiers determine what part of the code can access the class members. C++ has three access modifiers:

  • public: Members marked as public can be accessed from anywhere.
  • private: Members marked as private can only be accessed from within the class.
  • protected: Members marked as protected can be accessed from within the class and its derived classes.

Here is an example of a class with public and private members:

#include <iostream>

class Square {
private:
  int sideLength;

public:
  Square(int l) {
    sideLength = l;
  }

  int getArea() {
    return sideLength * sideLength;
  }
};

int main() {
  Square s(5);
  std::cout << "Area of Square: " << s.getArea() << std::endl;
  return 0;
}

Getters and Setters

In C++, getters and setters methods allow you to get or set the value of an object's private member variables.

Here is a quick reference for how to define and use getters and setters in C++:

Defining Getters

To define a getter method for a private member variable x, you can use the following syntax:

class MyClass {
private:
  int x;

public:
  int getX() const {
    return x;
  }
};

The const keyword at the end of the method declaration indicates that the getter method does not modify the object's state.

Defining Setters

To define a setter method for a private member variable x, you can use the following syntax:

class MyClass {
private:
  int x;

public:
  void setX(int newX) {
    x = newX;
  }
};

Using getters and setters

To use a getter method, you can call it a regular member function on an object of the class.

Example

MyClass obj;
int x = obj.getX();

To use a setter method, you can call it like a regular member function on an object of the class, passing in the new value as an argument. For example

MyClass obj;
obj.setX(10);

OOP Concepts

Inheritance

Inheritance is the process of creating a new class that is a modified version of an existing class. The new class is called the derived class, and the existing class is the base class.

Inheritance helps create new classes that can reuse the code and data of the existing classes.

class Vehicle {
    // drive() function
};

class Bike: public Vehicle {
    // ride() function
};

Vehicle is a base class that defines a drive() function. Bike is a derived class of Vehicle that inherits the drive() function from the base class and adds its own ride() function.

The public access specifier indicates that the base class members are inherited as public members in the derived class.

So, the drive() function can be accessed directly from an object of the Bike class.


Polymorphism

Polymorphism is the ability of a function or object to take on multiple forms. In C++, polymorphism is achieved through the use of virtual functions and function overriding.

#include <iostream>

class Animal {
 public:
  virtual void makeSound() = 0;
};

class Cat : public Animal {
 public:
  void makeSound() override { std::cout << "Meow!" << std::endl; }
};

class Dog : public Animal {
 public:
  void makeSound() override { std::cout << "Woof!" << std::endl; }
};

int main() {
  Cat cat;
  Dog dog;
  Animal& animal1 = cat;
  Animal& animal2 = dog;
  animal1.makeSound();
  animal2.makeSound();
  return 0;
}

In this example, the Animal class is an abstract base class that has a pure virtual function called makeSound().

The Cat and Dog classes are derived from the Animal class and provide their own implementation of the makeSound() function.


Encapsulation

Encapsulation is a simple concept of wrapping similar code in one code block.

C++ allows us to bundle data members and functions that operate together inside a single class.

Example

class Rectangle {
  public:
    int length;
    int breadth;

    int getArea() {
      return length * breadth;
    }
};

Abstraction

Abstraction is the process of hiding the implementation details of a class and exposing only the necessary interface to the user.

In C++, abstraction is achieved through the use of abstract classes and pure virtual functions.

An abstract class is defined using the virtual keyword in the function declaration but with no function definition.

Example

class Shape {
 public:
  // Pure virtual function
  virtual double area() = 0;
};

File Handling

File Handling involves the following:

  • Opening a File
  • Closing a File
  • Reading From a File
  • Writing to a File

Opening a File

#include <fstream>

// Open a file for input
std::ifstream in_file;
in_file.open("filename.txt");

// Open a file for output
std::ofstream out_file;
out_file.open("filename.txt");

// Open a file for input and output
std::fstream io_file;
io_file.open("filename.txt");

Here, we have opened a file for input (writing), output(reading), and io (both). Do remember to include the fstream header file while doing any file operation.


Closing a File

in_file.close();
out_file.close();
io_file.close();

Here, we have closed all three files we opened in the prior example.


Reading from a File

#include <string>

std::string line;

// Read a single line from the file
std::getline(in_file, line);

// Read a character from the file
char c = in_file.get();

// Read a block of data from the file
char buffer[1024];
in_file.read(buffer, 1024);

We can read a line, a character, or a data block from a file. Since all of these are string operations, we need to include the string header file for reading content from a file.


Writing to a file

#include <string>

// Write a string to the file
out_file << "Hello, world!" << std::endl;

// Write a character to the file
out_file.put('A');

Let us now see file handling in action with a simple C++ program:

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

int main() {
  // Open a file for output
  std::ofstream out_file;
  out_file.open("output.txt");

  // Write to the file
  out_file << "Hello, world!" << std::endl;
  out_file << "This is a test." << std::endl;

  // Close the file
  out_file.close();

  // Open the file for input
  std::ifstream in_file;
  in_file.open("output.txt");

  // Read from the file
  std::string line;
  while (std::getline(in_file, line)) {
    std::cout << line << std::endl;
  }

  // Close the file
  in_file.close();

  return 0;
}

Arrays

Arrays are fixed-size collections of elements of the same data type. To declare an array, you must specify the array's data type, name, and size.

Declaring Arrays

int numbers[5]; // declares an array of size 5 of type int

Initializing Arrays

int numbers[5] = {1, 2, 3, 4, 5}; // initializes the array with values 1, 2, 3, 4, 5

Accessing Array Elements

An important piece of information to remember about arrays is that they always start at the 0th index. So, in our case, numbers[0] will have the first element of the array.

int x = numbers[2]; // x is now 3 

Modifying Array Elements

numbers[3] = 7; // myArray is now {1, 2, 3, 7, 5}

Iterating Arrays

for (int i = 0; i < 5; i++) {
  cout << numbers[i] << endl;
}

Example

#include <iostream>

using namespace std;

int main() {
    
        int numbers[5] = {1, 2, 3, 4, 5};
        
        cout << "The first element of the array is " << numbers[0];
        cout << "\nThe second element of the array is " << numbers[1];
        cout << "\nThe element element of the array is " << numbers[4] <<"\n";
        
        cout << "\nThe elements of the array are: \n";
        for (int i = 0; i < 5; i++) {
            cout << numbers[i] << endl;
        }
        
        numbers[3] = 7;
        numbers[4] = 10;
        cout << "\nThe array is now modified to: \n";
         for (int i = 0; i < 5; i++) {
            cout << numbers[i] << endl;
        }
    return 0;
}

The C++ program above declares an array of integers called numbers with 5 elements and initializes it with the values {1, 2, 3, 4, 5}.

It then uses the cout function to print out the array's first, second, and last elements.

After this, the code uses a for loop to iterate through all the elements of the array and prints them out.

Finally, it modifies the third and fourth elements of the array by assigning them new values (7 and 10, respectively) and prints out the modified array using another for loop.


Vectors

Vectors are dynamic arrays that can store a variable number of elements. To use vectors, you need to include the vector header file.

#include <vector>
#include <iostream>

using namespace std;

int main(){
    vector<int> numbers; // initialize a vector

    // Add elements to the vector
    numbers.push_back(10);
    numbers.push_back(20);
    numbers.push_back(30);

    // Access elements in the vector
    cout << "First element: " << numbers[0] << endl;
    cout << "Second element: " << numbers[1] << endl;
    cout << "Third element: " << numbers[2] << endl;

    return 0;
}

The above C++ program demonstrates how to use vectors in C++.

In the main() function, a vector of integers called numbers is initialized using the default constructor.

Next, three elements are added to the vector using the push_back() method, which appends the element to the end of the vector.

Finally, the elements of the vector are accessed and printed.