named vs nameless objects in C++, again

This is an obscure point only relevant to compilers….

In C, a local variable on stack refers to a named object. That memory location holds an int (or a char or a struct or whatever) and has a unique name like “dog1”. The variable, the object (with its address) are 2 sides of the same coin. As stated elsewhere on this blog, the variable has a limited scope and the object has a limited lifespan. Well defined rules. In C++, you can create a reference to dog1. You get an alias to the object, whose real name is still dog1. Pretty simple so far. Things gets complicated with heap (aka free store or DynamicallyAllocatedMemory DAM).

If an object is a field named “age” in another object “person2” (a class/struct instance), and person2 lives on heap, then it’s fair to say this nested heap object has a name “age” [1].

If an object lives on heap (I call it a “heapy thingy”) and is Not a field, then it can’t have a name. Such an object is created by new() and new() only returns an address. Multiple pointer Variables can hold the same address, but have different variable names. Pointee object remains forever nameless.

Revisiting [1], person2 is actually a heap object identified by a pointer Variable, so another pointer Variable (say ptr2) can also refer to the same object. Therefore “person2” is just one of the pointer variable names, not the pointee object’s name since the pointee is on heap and therefore nameless.

Taking another look at the “age” field, person2->age and ptr2->age both refer to the same age object so it gets 2 names.

The nameless heap object is dominant in java (reference types) and c# (reference types). P36 [[c# primer]] puts it nicely — “Reference-type object consists of 2 parts: 1) named handle that we manipulate in our program, 2) unnamed object allocated on the managed heap….. A value type object is not represented as a handle/object pair.”

The upshot — a stack object has one controlling variable (hence a real name), whereas a heapy thingy is a puppet pulled by many strings.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s