const_cast
OperatorThe 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.
const_cast<type*>(expression)
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 is a mechanism for dealing with runtime errors to prevent resource leakage and centralize error handling.