How does the C++ compiler understand the pointer type? As I know pointer has a size equal to WORD of the OS (32 or 64). So does it store some info in that 32 (or 64) bits about type? Just because you can not have a pointer on one type and assign to that pointer another pointer with a different type.
A pointer is usually just a memory address on x86 based architectures (I don't know about other architectures). The compiler enforces type safety with different pointers at compile time - since it makes no sense to assign a pointer-to-char to a pointer-to-int, for example, especially since the objects pointed to are different sizes (so you'd be grabbing random memory if you accessed them). You can explicitly override this and assign any pointer to any other pointer with a reinterpret_cast<T>
, or with other types of cast like static_cast<T>
and dynamic_cast<T>
(the latter two are generally recommended due to being 'safer' but each have their uses).
So at the machine level a memory address is just a memory address and the CPU will dutifully carry out any accesses or calls on that. However it's dangerous, since you can get types mixed up and possibly not know about it. The compile time checks help avoid that, but there is not usually any information about the actual types stored inside the pointer itself at runtime.
An advantage of using iterators (pointer wrappers provided by the STL) is that many implementations have a lot of additional checks which can be enabled at runtime: like checking you're using the right container, that when you compare them they're the same type of iterator, and so on. This is a major reason to use iterators over pointers - but it's not required by the standard, so check your implementation.