In C++ primitive types, (bool, char, short, int, long, double, float) are values that can be directly stored in CPU registers.
When the CPU gets to the declaration of your variable, it acquires RAM to store the value. In C++11 and later the additional step of value-initialization is taken.
To break down your code:
int x = 1;
This will acquire enough RAM for an int (usually 4 bytes), associates the symbol x with the address of the acquired RAM and assigns the RAM at that address the value 1.
int p = x;
This will acquire enough RAM for another int, associate it with the symbol p, and copy the value stored at the address associated with the symbol x into the RAM at the new address.
p = 2;
This goes to the RAM address associated with the symbol p, and overwrites the value there with 2.
int a = int();
This acquires an another int-sized piece of RAM, associates the address of the RAM with a, calls the no-argument int conversion function, and assigns the return value (0) to the RAM at the address of a.
Enter pointers
To get deeper into the underlying mechanics, C++ allocates memory for variables in two locations in RAM: the stack and the heap.
When you declare a variable with the syntax int g;
, the associated ram is a stack address, and is acquired for use when the scope (a section of code delimited by {}
) the variable is declared in is entered, and remains allocated until the scope is exited, at which point it is deallocated.
Pointers operate similarly:
If you declare
int* k;
the space for a pointer is allocated on the stack, and the value at the address is either garbage, or with C++11 value-initialized to null. To assign an object to a pointer, you use the new
operator,
k = new int(2)
which allocates enough heap RAM to hold an int, initializes that RAM with the value 2, and assigns the address of the allocated RAM as a value at the stack address of k.