DEV Community

Cover image for C++ Code Snippets :)
Madhav Ganesan
Madhav Ganesan

Posted on • Updated on • Originally published at madhavganesan.hashnode.dev

C++ Code Snippets :)

Datatypes

#include <iostream>
using namespace std;

enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

struct Person {
    string name;
    int age;
};

class Rectangle {
private:
    int width, height;

public:
    void setDimensions(int w, int h) {
        width = w;
        height = h;
    }

    int area() {
        return width * height;
    }
};

int main() {
    //Primitive Datatypes
    char c = 'A';        // Character
    int num = 100;       // Integer
    short s = 10;        // Short Integer
    float f = 5.5f;      // Floating point
    double d = 10.99;    // Double precision floating 
    long l = 1234567890; // Long Integer
    bool b = true;       // Boolean

    //Derived Datatypes
    int arr[5] = {1, 2, 3, 4, 5}; // Array
    int *ptr = &num; // Pointer to an integer

    //Enumeration
    Day today = Wednesday;

    //User defined datatyeps
    //struct
    Person person;
    person.name = "Alice";
    person.age = 30;

    //class
    Rectangle rect;
    rect.setDimensions(5, 10);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode
#include <cstdio>

int main() {
    int a;
    long b;
    char c;
    float d;
    double e;

    // Read input values using scanf
    scanf("%d %ld %c %f %lf", &a, &b, &c, &d, &e);

    // Print values using printf
    printf("%d\n", a);
    printf("%ld\n", b);
    printf("%c\n", c);
    printf("%f\n", d);
    printf("%lf\n", e);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Initialization

#include <iostream>
using namespace std;

int main() {
    int num;
    int num1=0;
    cout<<num; //returns 0
    cout<<num1; //returns 0
}
Enter fullscreen mode Exit fullscreen mode

Basic Input/Output

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "You entered: " << num << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

For Loop

#include <iostream>
using namespace std;

int main() {
    for (int i = 0; i < 10; ++i) {
        cout << i << " ";
    }
    cout << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

While Loop

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    while (i < 10) {
        cout << i << " ";
        ++i;
    }
    cout << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Functions

#include <iostream>
using namespace std;

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

int main() {
    int result = add(5, 3);
    cout << "Sum: " << result << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Pass by reference:

#include <iostream>
using namespace std;

struct Person {
    string name;
    int age;
};

//num - int datatype
//Day - enum
//Person - struct
//array - int* arr - for array, we use pointers reference

void increment(int &num, Day &day, Person &person, int* arr) {
    num++;
}

int main(){
return 0;
}
Enter fullscreen mode Exit fullscreen mode

Keyword

auto

It allows the compiler to automatically deduce the type of a variable from its initializer

int main() {
    map<string, int> ages = {{"Alice", 30}, {"Bob", 25}};

    for (auto it = ages.begin(); it != ages.end(); ++it) {
        cout << it->first << ": " << it->second << endl;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

static

  1. Static Variables Inside Functions A static variable inside a function retains its value between function calls. It is initialized only once, and its lifetime extends across the entire program run.
#include <iostream>
using namespace std;

void increment() {
    static int count = 0; // Static variable
    count++;
    cout << "Count: " << count << endl;
}

int main() {
    increment(); // Count: 1
    increment(); // Count: 2
    increment(); // Count: 3
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
  1. Static Variables Inside Classes static is used to declare static member variables, which are shared among all instances of the class and can be called using the class name.
#include <iostream>

class MyClass {
public:
    static int staticVar; // Declaration of static member variable
    static void staticFunc() { // Declaration of static member function
        std::cout << "Static function called\n";
    }
};

// Definition of static member variable
int MyClass::staticVar = 0;

int main() {
    // Accessing static member variable
    MyClass::staticVar = 5;
    std::cout << "Static variable value: " << MyClass::staticVar << std::endl;

    // Calling static member function
    MyClass::staticFunc();

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

const

The const keyword in C++ is used to declare constants or to specify that something is read-only and cannot be modified. When used with a variable, it indicates that the variable's value cannot be changed after initialization.

const int SIZE = 10; // SIZE is a constant with value 10
Enter fullscreen mode Exit fullscreen mode

Classes and Objects

#include <iostream>
using namespace std;

class Rectangle {
private:
    int width, height;
public:
    Rectangle(int w, int h) : width(w), height(h) {}

    int area() const {
        return width * height;
    }
};

int main() {
    Rectangle rect(5, 3);
    cout << "Area: " << rect.area() << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Types of classes

Basic Class:

class BasicClass {
public:
    int data;
    void display() {
        std::cout << "Data: " << data << std::endl;
    }
};
Enter fullscreen mode Exit fullscreen mode

Abstract Class: A class that contains at least one pure virtual function. It cannot be instantiated directly and is typically used as a base class for other derived classes.

class AbstractClass {
public:
    virtual void pureVirtualFunction() = 0;  // Pure virtual function
};
Enter fullscreen mode Exit fullscreen mode

Derived Class: A class that inherits properties and behaviors from a base class

class BaseClass {
public:
    void baseFunction() {
        std::cout << "Base function" << std::endl;
    }
};

class DerivedClass : public BaseClass {
public:
    void derivedFunction() {
        std::cout << "Derived function" << std::endl;
    }
};
Enter fullscreen mode Exit fullscreen mode

Friend Class: A class that is granted access to the private and protected members of another class.

class FriendClass;

class BaseClass {
private:
    int secretData;
    friend class FriendClass;  // Friend class declaration
};

class FriendClass {
public:
    void accessSecret(BaseClass& obj) {
        std::cout << "Secret Data: " << obj.secretData << std::endl;
    }
};
Enter fullscreen mode Exit fullscreen mode

Singleton class:
A singleton class ensures that only one instance of the class exists throughout the lifetime of the application. This is useful when exactly one object is needed to coordinate actions across the system, such as logger, a configuration manager, or a database connection.

#include <iostream>

class Singleton {
private:
    // Private constructor to prevent instantiation
    Singleton() {
        std::cout << "Singleton instance created" << std::endl;
    }

    // Deleted copy constructor and assignment operator to prevent copying
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

public:
    // Static method to provide access to the single instance
    static Singleton& getInstance() {
        static Singleton instance; // Guaranteed to be destroyed and instantiated on first use
        return instance;
    }

    void showMessage() {
        std::cout << "Hello from Singleton" << std::endl;
    }
};

int main() {
    // Access the singleton instance and call a method
    Singleton& singleton = Singleton::getInstance();
    singleton.showMessage();

    // Uncommenting the following lines will cause compilation errors
    // Singleton anotherInstance = Singleton::getInstance(); // Copy constructor is deleted
    // Singleton anotherInstance; // Constructor is private
    // Singleton* ptr = new Singleton(); // Constructor is private

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Anonymous Class
In C++, there is no direct support for anonymous classes (classes without a name)

#include <iostream>

int main() {
    // Define and instantiate an unnamed class
    struct {
        void showMessage() {
            std::cout << "Hello from an unnamed class";
        }
    } anonymousClassInstance;

    // Call the method
    anonymousClassInstance.showMessage();

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Destructor

A destructor in C++ is a special member function that is executed when an object goes out of scope or is explicitly deleted. The main purpose of a destructor is to release resources that the object may have acquired during its lifetime

#include <iostream>

class SimpleClass {
public:
    // Constructor
    SimpleClass() {
        std::cout << "Constructor: Object created" << std::endl;
    }

    // Destructor
    ~SimpleClass() {
        std::cout << "Destructor: Object destroyed" << std::endl;
    }
};

int main() {
    std::cout << "Entering main function" << std::endl;
    {
        SimpleClass obj; // Constructor is called here
    } // Destructor is called here when obj goes out of scope
    std::cout << "Exiting main function" << std::endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Virtual function

A virtual function is a member function in a base class that you expect to override in derived classes. When you use a virtual function, it ensures that the function call is resolved at runtime based on the actual object type

#include <iostream>

class Base {
public:
    virtual void show() {
        std::cout << "Base class show function" << std::endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        std::cout << "Derived class show function" << std::endl;
    }
};

int main() {
    Base* basePtr = new Derived(); // Base class pointer to Derived class object
    basePtr->show();              // Calls Derived class show function
    delete basePtr;               // Correctly calls Derived and Base destructors
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Inheritance

#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() const {
        cout << "Drawing a shape" << endl;
    }
};

class Circle : public Shape {
public:
    void draw() const override {
        cout << "Drawing a circle" << endl;
    }
};

int main() {
    Shape* shape = new Circle();
    shape->draw();
    delete shape;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Standard Library Containers

Vector

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};
    vec.push_back(6);

    for (int num : vec) {
        cout << num << " ";
    }
    sort(vec.begin(), vec.end());
    cout << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Priority Queue

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int main() {
    priority_queue<int> pq;

    // Insert elements
    pq.push(10);
    pq.push(30);
    pq.push(20);
    pq.push(5);
    pq.push(1);

    // Remove elements
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Map

#include <iostream>
#include <map>
#include <string>

using namespace std;

void printMap(const map<string, int>& m) {
    for (const auto& pair : m) {
        cout << pair.first << ": " << pair.second << endl;
    }
}

int main() {

    // Insert an element
    map<string, int> ageMap;
    ageMap.insert(make_pair("Alice", 30));
    ageMap.insert(pair<string, int>("Bob", 25));

    // Access an element
    for (const auto& pair : ageMap) {
        cout << pair.first << " is " << pair.second << " years old." << endl;
    }

    // Count elements
    if (ageMap.count("Alice")) {
        cout << "Alice is found in the map." << endl;
    } else {
        cout << "Alice is not found in the map." << endl;
    }

    // Find elements
    auto it = ageMap.find("Bob");
    if (it != ageMap.end()) {
        cout << "Found Bob, age: " << it->second << endl;
    } else {
        cout << "Bob is not found in the map." << endl;
    }

    //Assign a value
    ageMap["Charlie"] = 40;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

File I/O

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream outFile("example.txt");
    outFile << "Hello, file I/O!" << endl;
    outFile.close();

    ifstream inFile("example.txt");
    string line;
    while (getline(inFile, line)) {
        cout << line << endl;
    }
    inFile.close();

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Exception Handling

#include <iostream>
#include <stdexcept>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw invalid_argument("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        cout << "Result: " << result << endl;
    } catch (const invalid_argument& e) {
        cout << "Error: " << e.what() << endl;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Switch Statement

#include <iostream>
using namespace std;

int main() {
    int day = 3;
    switch (day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Invalid day" << endl;
            break;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Default Arguments:

Default argument is a value provided in a function declaration that is used when the caller of the function does not provide a corresponding argument.
(Note: The trailing argument will be the default argument)

void greet(std::string name = "Guest") {
    std::cout << "Hello, " << name << "!" << std::endl;
}

int main() {
    // Calling greet without providing any arguments
    greet(); // Output: Hello, Guest!

    // Calling greet with an argument
    greet("Alice"); // Output: Hello, Alice!

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Normal Pointers

Basic Pointer Usage

#include <iostream>
using namespace std;

int main() {
    int value = 10;
    int* ptr = &value;

    cout << "Value: " << *ptr << endl;
    cout << "Address of value: " << ptr << endl;

    *ptr = 20; // Modify the value using the pointer
    cout << "Modified Value: " << value << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Pointer Arithmetic

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int* ptr = arr;// ptr points to first address

    for (int i = 0; i < 5; ++i) {
        cout << *(ptr + i) << " ";
    }
    cout << endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Lower and Upper case:

#include <iostream>
#include <cctype>
using namespace std;

int main() {
    char one='G';
    char three='d';
    //returns ascii value
    cout<<tolower(one)<<endl;
    //returns lower case letter
    cout<<(char)tolower(one)<<endl;
    //returns upper case letter
    cout<<(char)toupper(three)<<endl;

    string two="HSLL";
    string res;
    for(char each:two){
        res+=(char)tolower(each);
    }
    cout<<res<<endl;

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Datatype Check

#include <iostream>
#include <cctype>  

int main() {
    char ch = '5';
    if (isalnum(ch)) {
        //alphanumeric 
    }else if (isdigit(ch)) {
        //numeric
    }else if (isalpha(ch)) {
        //alphabetic
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Conversion

#include <iostream>
#include <string>
using namespace std;

int main() {
    // String to Integer conversion
    string str = "1234";
    int num = stoi(str);

    // Integer to String conversion
    int anotherNum = 5678;
    string anotherStr = to_string(anotherNum);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Common Mistakes:

1)Avoid Division by Zero:
Division by zero is mathematically undefined and causes a program to crash or produce unpredictable results.

2)Overflow check:

Image description

    int reverse(int x) {
        int reverse = 0;
        int sign=1;
        if(x<0){
            sign=-1;
        }
        x = abs(x);

        while (x != 0) {
            int digit = x % 10;

            //Overflow check
            if (reverse > (INT_MAX - digit) / 10) {
                return 0;
            }
            reverse = reverse * 10 + digit;
            x /= 10; 
        }

        return reverse * sign;
    }
Enter fullscreen mode Exit fullscreen mode

Pragma

It is a directive that provides additional information to the compiler. Normally, variables are stored in memory in below fashion.

struct Test
{
   char AA;
   char CC;
   int BB;
};

|   1   |   2   |   3   |   4   |  

| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) |
| CC(1) | pad.................. |
Enter fullscreen mode Exit fullscreen mode

pragma pack(1)

|   1   |

| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |
Enter fullscreen mode Exit fullscreen mode

pragma pack(2)

|   1   |   2   |

| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
Enter fullscreen mode Exit fullscreen mode

Top comments (0)