const_cast Operator

The const_cast operator allows for the removal of the const, volatile, and __unaligned attributes from variables, primarily used when you need to modify a constant object.

Key Points:

Syntax:

const_cast<type*>(expression)

Example:

class Demo {
private:
    int value;
public:
    Demo(int val) : value(val) {}

    void display() const {
        cout << "Value: " << value << endl;
    }

    void setValue(int newVal) const {
        // Cannot directly modify value in const function
        // value = newVal; // Error!

        // Using const_cast to bypass const
        const_cast<Demo*>(this)->value = newVal;
    }
};

int main() {
    const Demo d(10);
    d.display(); // Output: Value: 10
    d.setValue(20); // Modifies the value using const_cast
    d.display(); // Output: Value: 20
    return 0;
}

Exception Handling

Exception handling is a mechanism for dealing with runtime errors to prevent resource leakage and centralize error handling.

Why Use Exception Handling:

  1. Avoids resource leakage
  2. Centralized handling of runtime errors
  3. Separation of error detection and error handling

Key Components:

  1. try: Block of code that might throw exceptions
  2. catch: Handles exceptions thrown from the try block
  3. throw: Explicitly generates an exception

Basic Syntax: