Skip to main content
const_cast is a C++ type conversion operator explicitly designed to add or remove the const (constness) or volatile (volatility) qualifiers from a pointer, reference, or pointer-to-member type. It is the only C++ style cast capable of manipulating cv-qualifiers.

Syntax

  • new_type: Must be a pointer, reference, or pointer-to-member type.
  • expression: The value being cast. Its underlying base type must exactly match the base type of new_type.

Technical Mechanics and Rules

1. Strict Type Matching const_cast cannot change the underlying data type of the object. It only alters the cv-qualifiers. Attempting to cast between different base types (e.g., from const int* to char*) will result in a compiler error.
2. Pointer and Reference Restriction The operator operates exclusively on pointers, references, and pointers-to-members. It cannot be used to cast objects by value.
3. Adding vs. Removing Qualifiers While most commonly associated with casting away constness, const_cast is bidirectional. It can safely add const or volatile qualifiers to a non-qualified type, though an implicit conversion is usually sufficient for adding const.

Undefined Behavior (UB)

The most critical technical distinction regarding const_cast is the difference between the legality of the cast and the legality of the memory access. Using const_cast to strip the const qualifier from a pointer or reference is always valid C++. However, modifying the underlying object through the resulting pointer/reference invokes Undefined Behavior if the original object was declared as const. Well-Defined Behavior (Original object is non-const):
Undefined Behavior (Original object is const):

Compile-Time Evaluation

const_cast is a compile-time directive. It does not generate any executable machine code and incurs zero runtime overhead. It merely instructs the compiler’s type-checking system to treat the referenced memory address with a different set of cv-qualifiers for the duration of the expression.
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More