Accessing an object as the wrong type
suggest changeIn most cases, it is illegal to access an object of one type as though it were a different type (disregarding cv-qualifiers). Example:
float x = 42;
int y = reinterpret_cast<int&>(x);
The result is undefined behavior.
There are some exceptions to this strict aliasing rule:
- An object of class type can be accessed as though it were of a type that is a base class of the actual class type.
- Any type can be accessed as a
char
orunsigned char
, but the reverse is not true: a char array cannot be accessed as though it were an arbitrary type. - A signed integer type can be accessed as the corresponding unsigned type and vice versa.
A related rule is that if a non-static member function is called on an object that does not actually have the same type as the defining class of the function, or a derived class, then undefined behavior occurs. This is true even if the function does not access the object.
struct Base {
};
struct Derived : Base {
void f() {}
};
struct Unrelated {};
Unrelated u;
Derived& r1 = reinterpret_cast<Derived&>(u); // ok
r1.f(); // UB
Base b;
Derived& r2 = reinterpret_cast<Derived&>(b); // ok
r2.f(); // UB
Found a mistake? Have a question or improvement idea?
Let me know.
Accessing an object as the wrong type
Table Of Contents
2 Literals
9 Arrays
10 Flow control
12 Loops
15 keywords
17 auto keyword
18 Pointers
21 std::string
22 Enumeration
24 std::vector
25 std::array
26 std::pair
27 std::map
30 std::any
31 std::variant
36 std::iomanip
37 Iterators
38 Basic I/O
39 File I/O
40 Streams
44 References
45 Polymorphism
52 Unions
53 Templates
54 Namespaces
57 Lambdas
58 Threading
60 Preprocessor
61 SFINAE
63 RAII
64 Exceptions
68 Sorting
75 Pimpl idiom
76 Copy elision
79 Singleton
82 Type erasure
85 RTTI
88 Scopes
89 Atomic types
91 constexpr
99 Type traits
103 Attributes
105 Profiling
108 Recursion
109 Callable objects
112 Inline functions
114 Header files
117 Parameter packs
118 Iteration
119 type deduction
121 Build systems
123 Type inference
126 Alignment
127 Inline variables
134 Optimization
135 Semaphore
137 Debugging
140 Mutexes
141 Recursive mutex
142 Unit testing
143 decltype
144 Digit separators
145 C++ Containers
147 Contributors