C++

Basic Syntax

  • Comments

    // Single line comment
    /* Multi-line comment */
  • Headers

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

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

Data Types

  • Primitive Types

    int, float, double, char, bool
  • String

    std::string str = "Hello, World!";
  • Vectors

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

Control Structures

  • If-Else

    if (condition) {
        // code
    } else {
        // code
    }
  • Switch

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

    // 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

    void myFunction() {
        // code
    }
    
    int add(int a, int b) {
        return a + b;
    }
  • Function Overloading

    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

    class MyClass {
    public:
        int myNum;
        std::string myString;
    
        void myMethod() {
            // code
        }
    };
  • Constructor and Destructor

    class MyClass {
    public:
        MyClass() { // Constructor
            // code
        }
    
        ~MyClass() { // Destructor
            // code
        }
    };
  • Inheritance

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

Pointers and Memory Management

  • Pointers

    int var = 10;
    int* ptr = &var; // Pointer to var
    
    std::cout << *ptr; // Dereference pointer
  • Dynamic Memory Allocation

    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

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

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

String Manipulation

  • Concatenation

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

    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

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

Useful Libraries for Security

  • Crypto++ (Cryptographic library)

    #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)

    #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)

    #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;
    }
  • Buffer Overflow Prevention

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

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

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

    #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;
    }

Last updated

Was this helpful?