I'm trying to understand how type information is stored in memory.
We often say that an 8-bit value can store 2⁸ = 256 different values. But I'm wondering — when we create an object of that type, doesn't the information about the type itself (e.g., "this is an integer") also occupy space in memory?
In other words, if I have an 8-bit object, are only 8 bits used in memory? Or is additional memory used to store the object's type metadata? How does this differ between low-level languages (like C or C++) and high-level languages (like Python or JavaScript)?
This information isn't stored at runtime (except for polymorphic types, i.e. the classes with virtual
functions; for those look up "RTTI" and "vtables").
It is baked into the generated instructions. E.g. for:
void foo(int &x)
{
x += 42;
}
On the assembly level the function just receives a pointer, and x += 42;
compiles to "assume that the pointer points to an int
, and add 42
to it".
The code trusts that the pointer it receives actually points to an object of that type.
This is all for C/C++, of course. Interpreted languages like Python have to store the type information at runtime.