aug2uag
aug2uag

Reputation: 3445

Variable/object data structure in OO languages

In object oriented programming languages when you define a variable it ends up becoming a reference to an object. The variable is not itself the object, and instead points to the object that carries the value that was assigned to that variable.

Question is how does this work so efficiently? What is the mechanism of how a variable is assigned to an object?

The way I think about the organization is as a linked list, however could not find references how the data is structured in languages such as Ruby or Java.

Upvotes: 1

Views: 98

Answers (1)

jwalk
jwalk

Reputation: 1147

In object oriented programming languages when you define a variable it ends up becoming a reference to an object.

This is not always true. For example, C++ can be considered an object-oriented language, yet a user of the language can use a variable as a reference/pointer or explicitly as a value.

However, you are right in that some (typically higher-level) OO languages implicitly use references so that the user of the language does not have to worry about these kinds of implementation "details" in regards to performance. They try to take responsibility for this instead.

how does this work so efficiently? What is the mechanism of how a variable is assigned to an object?

Consider a simple example. What happens when an object is passed as a parameter to a function? A copy of that object must be made so that the function can refer to that object locally. For an OO language that implicitly uses references, only the address of the object needs to be copied, whereas a true pass-by-value would require a copy of the complete memory contents of the object, which could potentially be very large (think a collection of objects or similar).

A detailed explanation of this involves getting into the guts of assembly. For example, why does a copy of an object to a function call even need to be made in the first place? Why does the indirection of an address not take longer than a direct value? Etc.

Related

What's the difference between passing by reference vs. passing by value?

Upvotes: 1

Related Questions