> For the complete documentation index, see [llms.txt](https://docs.hackerspot.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hackerspot.net/cheatsheets/coding/c++.md).

# C++

### **Basic Syntax**

* **Comments**

  ```cpp
  // Single line comment
  /* Multi-line comment */
  ```
* **Headers**

  ```cpp
  #include <iostream> // Standard input-output stream
  #include <string>   // String library
  #include <vector>   // Vector library
  #include <fstream>  // File stream
  #include <sstream>  // String stream
  ```
* **Main Function**

  ```cpp
  int main() {
      // code
      return 0;
  }
  ```

### **Data Types**

* **Primitive Types**

  ```cpp
  int, float, double, char, bool
  ```
* **String**

  ```cpp
  std::string str = "Hello, World!";
  ```
* **Vectors**

  ```cpp
  std::vector<int> vec = {1, 2, 3, 4};
  ```

### **Control Structures**

* **If-Else**

  ```cpp
  if (condition) {
      // code
  } else {
      // code
  }
  ```
* **Switch**

  ```cpp
  switch (expression) {
      case value1:
          // code
          break;
      case value2:
          // code
          break;
      default:
          // code
  }
  ```
* **Loops**

  ```cpp
  // For loop
  for (int i = 0; i < 10; ++i) {
      // code
  }

  // While loop
  while (condition) {
      // code
  }

  // Do-while loop
  do {
      // code
  } while (condition);
  ```

### **Functions**

* **Basic Function**

  ```cpp
  void myFunction() {
      // code
  }

  int add(int a, int b) {
      return a + b;
  }
  ```
* **Function Overloading**

  ```cpp
  void print(int i) {
      std::cout << i << std::endl;
  }

  void print(double f) {
      std::cout << f << std::endl;
  }

  void print(std::string str) {
      std::cout << str << std::endl;
  }
  ```

### **Object-Oriented Programming**

* **Class**

  ```cpp
  class MyClass {
  public:
      int myNum;
      std::string myString;

      void myMethod() {
          // code
      }
  };
  ```
* **Constructor and Destructor**

  ```cpp
  class MyClass {
  public:
      MyClass() { // Constructor
          // code
      }

      ~MyClass() { // Destructor
          // code
      }
  };
  ```
* **Inheritance**

  ```cpp
  class Base {
  public:
      void baseMethod() {
          // code
      }
  };

  class Derived : public Base {
  public:
      void derivedMethod() {
          // code
      }
  };
  ```

### **Pointers and Memory Management**

* **Pointers**

  ```cpp
  int var = 10;
  int* ptr = &var; // Pointer to var

  std::cout << *ptr; // Dereference pointer
  ```
* **Dynamic Memory Allocation**

  ```cpp
  int* ptr = new int;
  *ptr = 10;

  delete ptr; // Deallocate memory

  int* arr = new int[10];
  delete[] arr; // Deallocate array
  ```

### **File I/O**

* **Reading from a File**

  ```cpp
  std::ifstream inFile("example.txt");
  std::string line;
  while (std::getline(inFile, line)) {
      std::cout << line << std::endl;
  }
  inFile.close();
  ```
* **Writing to a File**

  ```cpp
  std::ofstream outFile("example.txt");
  outFile << "Hello, World!" << std::endl;
  outFile.close();
  ```

### **String Manipulation**

* **Concatenation**

  ```cpp
  std::string str1 = "Hello, ";
  std::string str2 = "World!";
  std::string str3 = str1 + str2;
  ```
* **Finding Substring**

  ```cpp
  std::string str = "Hello, World!";
  std::size_t found = str.find("World");
  if (found != std::string::npos)
      std::cout << "Found 'World' at: " << found << std::endl;
  ```
* **Substring**

  ```cpp
  std::string str = "Hello, World!";
  std::string sub = str.substr(7, 5); // "World"
  ```

### **Useful Libraries for Security**

* **Crypto++ (Cryptographic library)**

  ```cpp
  #include <cryptopp/sha.h>
  #include <cryptopp/hex.h>

  std::string sha256(const std::string& input) {
      CryptoPP::SHA256 hash;
      std::string digest;

      CryptoPP::StringSource s(input, true,
          new CryptoPP::HashFilter(hash,
              new CryptoPP::HexEncoder(
                  new CryptoPP::StringSink(digest), true)));

      return digest;
  }
  ```
* **Boost Libraries (General-purpose libraries)**

  ```cpp
  #include <boost/algorithm/string.hpp>

  std::string to_upper(const std::string& str) {
      std::string result;
      boost::to_upper_copy(std::back_inserter(result), str);
      return result;
  }
  ```
* **Poco (Network and other utilities)**

  ```cpp
  #include <Poco/Net/HTTPClientSession.h>
  #include <Poco/Net/HTTPRequest.h>
  #include <Poco/Net/HTTPResponse.h>
  #include <Poco/StreamCopier.h>
  #include <iostream>
  #include <string>

  void http_get(const std::string& host, const std::string& path) {
      Poco::Net::HTTPClientSession session(host);
      Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path);
      session.sendRequest(request);

      Poco::Net::HTTPResponse response;
      std::istream& rs = session.receiveResponse(response);
      std::string responseBody;
      Poco::StreamCopier::copyToString(rs, responseBody);
      std::cout << responseBody << std::endl;
  }
  ```

### **Common Security-Related Tasks**

* **Buffer Overflow Prevention**

  ```cpp
  char buffer[10];
  std::strncpy(buffer, input.c_str(), sizeof(buffer) - 1);
  buffer[sizeof(buffer) - 1] = '\0'; // Null-terminate
  ```
* **Input Validation**

  ```cpp
  bool is_valid_input(const std::string& input) {
      // Implement validation logic (e.g., regex)
      return true; // or false based on validation
  }
  ```
* **Secure File Handling**

  ```cpp
  std::ifstream inFile("example.txt", std::ios::binary);
  if (!inFile) {
      std::cerr << "Error opening file!" << std::endl;
      return;
  }
  ```
* **Hashing and Encryption (Using Crypto++)**

  ```cpp
  #include <cryptopp/sha.h>
  #include <cryptopp/hex.h>
  #include <cryptopp/aes.h>
  #include <cryptopp/filters.h>
  #include <cryptopp/modes.h>

  std::string sha256(const std::string& input) {
      CryptoPP::SHA256 hash;
      std::string digest;

      CryptoPP::StringSource s(input, true,
          new CryptoPP::HashFilter(hash,
              new CryptoPP::HexEncoder(
                  new CryptoPP::StringSink(digest), true)));

      return digest;
  }

  std::string encrypt_aes(const std::string& plaintext, const std::string& key) {
      std::string ciphertext;
      CryptoPP::AES::Encryption aesEncryption((byte*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
      CryptoPP::ECB_Mode_ExternalCipher::Encryption ecbEncryption(aesEncryption);

      CryptoPP::StringSource(plaintext, true,
          new CryptoPP::StreamTransformationFilter(ecbEncryption,
              new CryptoPP::StringSink(ciphertext)));

      return ciphertext;
  }
  ```
