C++ Code Snippets :)

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

Initialization

#include <iostream>
using namespace std;

int main() {
    int num;
    int num1=0;
    cout<<num; //returns 0
    cout<<num1; //returns 0
}

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

For Loop

#include <iostream>
using namespace std;

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

While Loop

#include <iostream>
using namespace std;

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

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

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

Keyword

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

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

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

Types of classes

Basic Class:

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

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

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

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

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

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

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

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

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

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 << " ";
    }
    cout << endl;

    return 0;
}

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

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

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

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

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

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

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

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