Home

The Difference Between Values and References in JavaScript

In JavaScript, you can pass by value and by reference.

The main difference between the two is that passing by value happens when assigning primitives while passing by reference when assigning objects.

Let's discuss values and references in more detail in this post.

1. Understanding primitive and objects

JavaScript provides 2 categories of data types: primitives and objects .

The primitives are numbers, booleans, strings, symbols, and special values null and undefined .

The second category is objects. Particularly the plain object, arrays, functions, and more — are all objects.

Saying it differently, anything that is not a primitive value is an object.

The simple rule of passing by value is that all primitive values in JavaScript are passed by value. Simple as that.

Passing by value means that every time you assign a value to a variable, a copy of that value is created. Every single time.

Let me show you how pass by value manifests itself.

Let's say you have 2 variables a and b :

The first statement let a = 1 defines a variable a initialized with the number 1 .

The second statement let b = a defines another variable b and initializes it with the value of a variable — which is passing by value. Simpler, a copy of the number 1 is assigned to b .

Later, b = b + 2 increases by 2 and becomes 3 . b variable changes, and this change doesn't affect the value of a .

3. References

The pass by reference, however, manifests itself differently.

When creating an object you're given a reference to that object. If 2 variables hold the same reference, then changing the object reflects in both variables.

Let's check the following code sample:

The first statement let x = [1] creates an array, defines a variable x , and initializes the variable with a reference to the created array.

Then let y = x defines a variable y , and initializes y with the reference stored in x variable. This is a pass by reference.

y.push(2) mutates the array by pushing an item 2 . Because x and y variables reference the same array, this change is reflected in both variables.

Note: for simplicity, I say that variables hold references to objects. But strictly saying variables in JavaScript hold values that are references to objects .

4. Comparing values and comparing references

Understanding the difference between values and references is important when you want to compare objects.

When using the strict comparison operator === , 2 variables having values are equal if they have the same value. All of the below comparisons are equal:

one and oneCopy have the same value 1 . The operator === evaluates to true as longs as both operands are 1 , no matter where the value is taken from: a literal 1 , variable's value, expression 2 - 1 .

But the comparison operator === works differently when comparing references. 2 references are equal only if they reference exactly the same object.

ar1 and ar2 hold references to different array instance:

ar1 and ar2 reference arrays of the same structure, however ar1 === ar2 evaluates to false because ar1 and ar2 reference different array objects.

The comparison operator returns true only when comparing references pointing to the same object: ar1 === ar11 or ar1 === ar1 .

In JavaScript primitive types are passed around as values: meaning that each time a value is assigned, a copy of that value is created.

On the other side objects (including plain objects, array, functions, class instances) are references. If you modify the object, then all variables that reference that object are going to see the change.

The comparison operator distinguishes comparing values and references. 2 variables holding references are equal only if they reference exactly the same object, but 2 variables holding values are equal if they simply have 2 same values no matter where the value originates: from a variable, literal, etc.

Often, however, you might want to compare objects by their structure rather than by reference. Check out the post How to Compare Objects in JavaScript .

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

All you need to know on by reference vs by value

All you need to know on by reference vs by value

by Szilard Magyar

gfKoji1a50mprGtRT9KEL4gPh6fNi6RGJ9CK

When it comes to software engineering there are quite a few misunderstood concepts and misused terms. By reference vs by value is definitely one of them.

I remember back in the day when I read up on the topic and every source I went through seemed to contradict the previous one. It took some time to get a solid grasp of it. I had no choice as it is a fundamental subject if you are a software engineer.

I ran into a nasty bug a few weeks back and decided to write an article so other people may have easier time figuring this whole thing out.

I code in Ruby on a daily basis. I also use JavaScript pretty often, so I have chosen these two languages for this presentation.

To understand all the concepts though we will use some Go and Perl examples as well.

To grasp the whole topic you have to understand 3 different things:

  • How the underlying data structures are implemented in the language (objects, primitive types, mutability,).
  • How variable assignment/copying/reassignment/comparison work

How variables are passed to functions

Underlying data types.

In Ruby there are no primitive types and everything is an object including integers and booleans.

And yes there is a TrueClass in Ruby.

These objects can be either mutable or immutable.

Immutable means there is no way you can change the object once it is created. There is just one instance for a given value with one object_id and it stays the same no matter what you do.

By default in Ruby the immutable object types are: Boolean , Numeric , nil , and Symbol .

In MRI the object_id of an object is the same as the VALUE that represents the object on the C level. For most kinds of objects this VALUE is a pointer to a location in memory where the actual object data is stored.

From now on we will use object_id and memory address interchangeably.

Let’s run some Ruby code in MRI for an immutable Symbol and a mutable String:

As you see while the symbol version keeps the same object_id for the same value, the string values belong to different memory addresses.

Unlike Ruby, JavaScript has primitive types.

They are — Boolean , null , undefined , String , and Number .

The rest of the data types go under the umbrella of Objects ( Array , Function , and Object) . There is nothing fancy here it is way more straightforward than Ruby.

Variable assignment , copying , reassignment and comparison

In Ruby every variable is just a reference to an object (since everything is an object).

When you assign a variable, it is a reference to an object not the object itself. When you copy an object b = a both variables will point to the same address.

This behavior is called copy by reference value .

Strictly speaking in Ruby and JavaScript everything is copied by value.

When it comes to objects though, the values happen to be the memory addresses of those objects. Thanks to this we can modify values that sit in those memory addresses. Again, this is called copy by reference value but most people refer to this as copy by reference.

It would be copy by reference if after reassigning a to ‘new string’, b would also point to the same address and have the same ‘new string’ value.

EDUJJ3qKxslYQaQU4HGqSfr4CJH5gwgu2e10

The same with an immutable type like Integer:

When you reassign a to the same integer, the memory address stays the same since a given integer always has the same object_id.

As you see when you compare any object to another one it is compared by value. If you wanna check out if they are the same object you have to use object_id.

Let’s see the JavaScript version:

Except the comparison — JavaScript uses by value for primitive types and by reference for objects. The behavior looks to be the same just like in Ruby.

Well, not quite.

Primitive values in JavaScript will not be shared between multiple variables . Even if you set the variables equal to each other. Every variable representing a primitive value is guaranteed to belong to a unique memory location.

This means none of the variables will ever point to the same memory address. It is also important that the value itself is stored in a physical memory location.

In our example when we declare b = a , b will point to a different memory address with the same ‘string’ value right away. So you don’t need to reassign a to point to a different memory address.

This is called copied by value since you have no access to the memory address only to the value.

-KYjFr8QIDdsGNMvjrsUac-V5KI6soar-ex3

Let’s see a better example where all this matters.

In Ruby if we modify the value that sits in the memory address then all the references that point to the address will have the same updated value:

You might think in JavaScript only the value of a would change but no. You can’t even change the original value as you don’t have direct access to the memory address.

You could say you assigned ‘x’ to a but it was assigned by value so a ’s memory address holds the value ‘x’, but you can’t change it as you have no reference to it.

The behavior of JavaScript objects and implementation are the same like Ruby’s mutable objects. Both copy be reference value.

JavaScript primitive types are copied by value. The behavior is the same like Ruby’s immutable objects which are copied by reference value .

Again, when you copy something by value it means you can’t change (mutate) the original value since there is no reference to the memory address. From the perspective of the writing code this is the same thing like having immutable entities that you can’t mutate.

If you compare Ruby and JavaScript the only data type that ‘behaves’ differently by default is String (that’s why we used String in the examples above).

In Ruby it is a mutable object and it is copied/passed by reference value while in JavaScript it is a primitive type and copied/passed by value.

When you wanna clone (not copy) an object you have to do it explicitly in both languages so you can make sure the original object won’t be modified:

It is crucial to remember this otherwise you will run into some nasty bugs when you invoke your code more than once. A good example would be a recursive function where you use the object as argument.

Another one is React (JavaScript front-end framework) where you always have to pass a new object for updating state as the comparison works based on object id.

This is faster because you don’t have to go through the object line by line to see if it has been changed.

Passing variables to functions is working the same way like copying for the same data types in most of the languages.

In JavaScript primitive types are copied and passed by value and objects are copied and passed by reference value.

I think this is the reason why people only talk about pass by value or pass by reference and never seem to mention copying. I guess they assume copying works the same way.

Now in JavaScript:

If you pass an object (not a primitive type like we did) in JavaScript to the function it works the same way like the Ruby example.

Object references and copying

One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, booleans, etc – are always copied “as a whole value”.

That’s easy to understand if we look a bit under the hood of what happens when we copy a value.

Let’s start with a primitive, such as a string.

Here we put a copy of message into phrase :

As a result we have two independent variables, each one storing the string "Hello!" .

Quite an obvious result, right?

Objects are not like that.

A variable assigned to an object stores not the object itself, but its “address in memory” – in other words “a reference” to it.

Let’s look at an example of such a variable:

And here’s how it’s actually stored in memory:

The object is stored somewhere in memory (at the right of the picture), while the user variable (at the left) has a “reference” to it.

We may think of an object variable, such as user , like a sheet of paper with the address of the object on it.

When we perform actions with the object, e.g. take a property user.name , the JavaScript engine looks at what’s at that address and performs the operation on the actual object.

Now here’s why it’s important.

When an object variable is copied, the reference is copied, but the object itself is not duplicated.

For instance:

Now we have two variables, each storing a reference to the same object:

As you can see, there’s still one object, but now with two variables that reference it.

We can use either variable to access the object and modify its contents:

It’s as if we had a cabinet with two keys and used one of them ( admin ) to get into it and make changes. Then, if we later use another key ( user ), we are still opening the same cabinet and can access the changed contents.

Comparison by reference

Two objects are equal only if they are the same object.

For instance, here a and b reference the same object, thus they are equal:

And here two independent objects are not equal, even though they look alike (both are empty):

For comparisons like obj1 > obj2 or for a comparison against a primitive obj == 5 , objects are converted to primitives. We’ll study how object conversions work very soon, but to tell the truth, such comparisons are needed very rarely – usually they appear as a result of a programming mistake.

An important side effect of storing objects as references is that an object declared as const can be modified.

It might seem that the line (*) would cause an error, but it does not. The value of user is constant, it must always reference the same object, but properties of that object are free to change.

In other words, the const user gives an error only if we try to set user=... as a whole.

That said, if we really need to make constant object properties, it’s also possible, but using totally different methods. We’ll mention that in the chapter Property flags and descriptors .

Cloning and merging, Object.assign

So, copying an object variable creates one more reference to the same object.

But what if we need to duplicate an object?

We can create a new object and replicate the structure of the existing one, by iterating over its properties and copying them on the primitive level.

We can also use the method Object.assign .

The syntax is:

  • The first argument dest is a target object.
  • Further arguments is a list of source objects.

It copies the properties of all source objects into the target dest , and then returns it as the result.

For example, we have user object, let’s add a couple of permissions to it:

If the copied property name already exists, it gets overwritten:

We also can use Object.assign to perform a simple object cloning:

Here it copies all properties of user into the empty object and returns it.

There are also other methods of cloning an object, e.g. using the spread syntax clone = {...user} , covered later in the tutorial.

Nested cloning

Until now we assumed that all properties of user are primitive. But properties can be references to other objects.

Now it’s not enough to copy clone.sizes = user.sizes , because user.sizes is an object, and will be copied by reference, so clone and user will share the same sizes:

To fix that and make user and clone truly separate objects, we should use a cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning” or “structured cloning”. There’s structuredClone method that implements deep cloning.

structuredClone

The call structuredClone(object) clones the object with all nested properties.

Here’s how we can use it in our example:

The structuredClone method can clone most data types, such as objects, arrays, primitive values.

It also supports circular references, when an object property references the object itself (directly or via a chain or references).

As you can see, clone.me references the clone , not the user ! So the circular reference was cloned correctly as well.

Although, there are cases when structuredClone fails.

For instance, when an object has a function property:

Function properties aren’t supported.

To handle such complex cases we may need to use a combination of cloning methods, write custom code or, to not reinvent the wheel, take an existing implementation, for instance _.cloneDeep(obj) from the JavaScript library lodash .

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

All operations via copied references (like adding/removing properties) are performed on the same single object.

To make a “real copy” (a clone) we can use Object.assign for the so-called “shallow copy” (nested objects are copied by reference) or a “deep cloning” function structuredClone or use a custom cloning implementation, such as _.cloneDeep(obj) .

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Pass by Reference in Python: Background and Best Practices

Pass by Reference in Python: Background and Best Practices

Table of Contents

Defining Pass by Reference

Contrasting pass by reference and pass by value, avoiding duplicate objects, returning multiple values, creating conditional multiple-return functions, understanding assignment in python, exploring function arguments, best practice: return and reassign, best practice: use object attributes, best practice: use dictionaries and lists.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Pass by Reference in Python: Best Practices

After gaining some familiarity with Python, you may notice cases in which your functions don’t modify arguments in place as you might expect, especially if you’re familiar with other programming languages. Some languages handle function arguments as references to existing variables , which is known as pass by reference . Other languages handle them as independent values , an approach known as pass by value .

If you’re an intermediate Python programmer who wishes to understand Python’s peculiar way of handling function arguments, then this tutorial is for you. You’ll implement real use cases of pass-by-reference constructs in Python and learn several best practices to avoid pitfalls with your function arguments.

In this tutorial, you’ll learn:

  • What it means to pass by reference and why you’d want to do so
  • How passing by reference differs from both passing by value and Python’s unique approach
  • How function arguments behave in Python
  • How you can use certain mutable types to pass by reference in Python
  • What the best practices are for replicating pass by reference in Python

Free Bonus: 5 Thoughts On Python Mastery , a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

Before you dive into the technical details of passing by reference, it’s helpful to take a closer look at the term itself by breaking it down into components:

  • Pass means to provide an argument to a function.
  • By reference means that the argument you’re passing to the function is a reference to a variable that already exists in memory rather than an independent copy of that variable.

Since you’re giving the function a reference to an existing variable, all operations performed on this reference will directly affect the variable to which it refers. Let’s look at some examples of how this works in practice.

Below, you’ll see how to pass variables by reference in C#. Note the use of the ref keyword in the highlighted lines:

As you can see, the refParameter of squareRef() must be declared with the ref keyword, and you must also use the keyword when calling the function. Then the argument will be passed in by reference and can be modified in place.

Python has no ref keyword or anything equivalent to it. If you attempt to replicate the above example as closely as possible in Python, then you’ll see different results:

In this case, the arg variable is not altered in place. It seems that Python treats your supplied argument as a standalone value rather than a reference to an existing variable. Does this mean Python passes arguments by value rather than by reference?

Not quite. Python passes arguments neither by reference nor by value, but by assignment . Below, you’ll quickly explore the details of passing by value and passing by reference before looking more closely at Python’s approach. After that, you’ll walk through some best practices for achieving the equivalent of passing by reference in Python.

When you pass function arguments by reference, those arguments are only references to existing values. In contrast, when you pass arguments by value, those arguments become independent copies of the original values.

Let’s revisit the C# example, this time without using the ref keyword. This will cause the program to use the default behavior of passing by value:

Here, you can see that squareVal() doesn’t modify the original variable. Rather, valParameter is an independent copy of the original variable arg . While that matches the behavior you would see in Python, remember that Python doesn’t exactly pass by value. Let’s prove it.

Python’s built-in id() returns an integer representing the memory address of the desired object. Using id() , you can verify the following assertions:

  • Function arguments initially refer to the same address as their original variables.
  • Reassigning the argument within the function gives it a new address while the original variable remains unmodified.

In the below example, note that the address of x initially matches that of n but changes after reassignment, while the address of n never changes:

The fact that the initial addresses of n and x are the same when you invoke increment() proves that the x argument is not being passed by value. Otherwise, n and x would have distinct memory addresses.

Before you learn the details of how Python handles arguments, let’s take a look at some practical use cases of passing by reference.

Using Pass by Reference Constructs

Passing variables by reference is one of several strategies you can use to implement certain programming patterns. While it’s seldom necessary, passing by reference can be a useful tool.

In this section, you’ll look at three of the most common patterns for which passing by reference is a practical approach. You’ll then see how you can implement each of these patterns with Python.

As you’ve seen, passing a variable by value will cause a copy of that value to be created and stored in memory. In languages that default to passing by value, you may find performance benefits from passing the variable by reference instead, especially when the variable holds a lot of data. This will be more apparent when your code is running on resource-constrained machines.

In Python, however, this is never a problem. You’ll see why in the next section .

One of the most common applications of passing by reference is to create a function that alters the value of the reference parameters while returning a distinct value. You can modify your pass-by-reference C# example to illustrate this technique:

In the example above, greet() returns a greeting string and also modifies the value of counter . Now try to reproduce this as closely as possible in Python:

counter isn’t incremented in the above example because, as you’ve previously learned, Python has no way of passing values by reference. So how can you achieve the same outcome as you did with C#?

In essence, reference parameters in C# allow the function not only to return a value but also to operate on additional parameters. This is equivalent to returning multiple values!

Luckily, Python already supports returning multiple values. Strictly speaking, a Python function that returns multiple values actually returns a tuple containing each value:

As you can see, to return multiple values, you can simply use the return keyword followed by comma-separated values or variables.

Armed with this technique, you can change the return statement in greet() from your previous Python code to return both a greeting and a counter:

That still doesn’t look right. Although greet() now returns multiple values, they’re being printed as a tuple , which isn’t your intention. Furthermore, the original counter variable remains at 0 .

To clean up your output and get the desired results, you’ll have to reassign your counter variable with each call to greet() :

Now, after reassigning each variable with a call to greet() , you can see the desired results!

Assigning return values to variables is the best way to achieve the same results as passing by reference in Python. You’ll learn why, along with some additional methods, in the section on best practices .

This is a specific use case of returning multiple values in which the function can be used in a conditional statement and has additional side effects like modifying an external variable that was passed in as an argument.

Consider the standard Int32.TryParse function in C#, which returns a Boolean and operates on a reference to an integer argument at the same time:

This function attempts to convert a string into a 32-bit signed integer using the out keyword . There are two possible outcomes:

  • If parsing succeeds , then the output parameter will be set to the resulting integer, and the function will return true .
  • If parsing fails , then the output parameter will be set to 0 , and the function will return false .

You can see this in practice in the following example, which attempts to convert a number of different strings:

The above code, which attempts to convert differently formatted strings into integers via TryParse() , outputs the following:

To implement a similar function in Python, you could use multiple return values as you’ve seen previously:

This tryparse() returns two values. The first value indicates whether the conversion was successful, and the second holds the result (or None , in case of failure).

However, using this function is a little clunky because you need to unpack the return values with every call. This means you can’t use the function within an if statement :

Even though it generally works by returning multiple values, tryparse() can’t be used in a condition check. That means you have some more work to do.

You can take advantage of Python’s flexibility and simplify the function to return a single value of different types depending on whether the conversion succeeds:

With the ability for Python functions to return different data types, you can now use this function within a conditional statement. But how? Wouldn’t you have to call the function first, assigning its return value, and then check the value itself?

By taking advantage of Python’s flexibility in object types, as well as the new assignment expressions in Python 3.8, you can call this simplified function within a conditional if statement and get the return value if the check passes:

Wow! This Python version of tryparse() is even more powerful than the C# version, allowing you to use it within conditional statements and in arithmetic expressions.

With a little ingenuity, you’ve replicated a specific and useful pass-by-reference pattern without actually passing arguments by reference. In fact, you are yet again assigning return values when using the assignment expression operator( := ) and using the return value directly in Python expressions.

So far, you’ve learned what passing by reference means, how it differs from passing by value, and how Python’s approach is different from both. Now you’re ready to take a closer look at how Python handles function arguments!

Passing Arguments in Python

Python passes arguments by assignment. That is, when you call a Python function, each function argument becomes a variable to which the passed value is assigned.

Therefore, you can learn important details about how Python handles function arguments by understanding how the assignment mechanism itself works, even outside functions.

Python’s language reference for assignment statements provides the following details:

  • If the assignment target is an identifier, or variable name, then this name is bound to the object. For example, in x = 2 , x is the name and 2 is the object.
  • If the name is already bound to a separate object, then it’s re-bound to the new object. For example, if x is already 2 and you issue x = 3 , then the variable name x is re-bound to 3 .

All Python objects are implemented in a particular structure. One of the properties of this structure is a counter that keeps track of how many names have been bound to this object.

Note: This counter is called a reference counter because it keeps track of how many references, or names, point to the same object. Do not confuse reference counter with the concept of passing by reference, as the two are unrelated.

The Python documentation provides additional details on reference counts .

Let’s stick to the x = 2 example and examine what happens when you assign a value to a new variable:

  • If an object representing the value 2 already exists, then it’s retrieved. Otherwise, it’s created.
  • The reference counter of this object is incremented.
  • An entry is added in the current namespace to bind the identifier x to the object representing 2 . This entry is in fact a key-value pair stored in a dictionary ! A representation of that dictionary is returned by locals() or globals() .

Now here’s what happens if you reassign x to a different value:

  • The reference counter of the object representing 2 is decremented.
  • The reference counter of the object that represents the new value is incremented.
  • The dictionary for the current namespace is updated to relate x to the object representing the new value.

Python allows you to obtain the reference counts for arbitrary values with the function sys.getrefcount() . You can use it to illustrate how assignment increases and decreases these reference counters. Note that the interactive interpreter employs behavior that will yield different results, so you should run the following code from a file:

This script will show the reference counts for each value prior to assignment, after assignment, and after reassignment:

These results illustrate the relationship between identifiers (variable names) and Python objects that represent distinct values. When you assign multiple variables to the same value, Python increments the reference counter for the existing object and updates the current namespace rather than creating duplicate objects in memory.

In the next section, you’ll build upon your current understanding of assignment operations by exploring how Python handles function arguments.

Function arguments in Python are local variables . What does that mean? Local is one of Python’s scopes . These scopes are represented by the namespace dictionaries mentioned in the previous section. You can use locals() and globals() to retrieve the local and global namespace dictionaries, respectively.

Upon execution, each function has its own local namespace:

Using locals() , you can demonstrate that function arguments become regular variables in the function’s local namespace. Let’s add an argument, my_arg , to the function:

You can also use sys.getrefcount() to show how function arguments increment the reference counter for an object:

The above script outputs reference counts for "my_value" first outside, then inside show_refcount() , showing a reference count increase of not one, but two!

That’s because, in addition to show_refcount() itself, the call to sys.getrefcount() inside show_refcount() also receives my_arg as an argument. This places my_arg in the local namespace for sys.getrefcount() , adding an extra reference to "my_value" .

By examining namespaces and reference counts inside functions, you can see that function arguments work exactly like assignments: Python creates bindings in the function’s local namespace between identifiers and Python objects that represent argument values. Each of these bindings increments the object’s reference counter.

Now you can see how Python passes arguments by assignment!

Replicating Pass by Reference With Python

Having examined namespaces in the previous section, you may be asking why global hasn’t been mentioned as one way to modify variables as if they were passed by reference:

Using the global statement generally takes away from the clarity of your code. It can create a number of issues, including the following:

  • Free variables, seemingly unrelated to anything
  • Functions without explicit arguments for said variables
  • Functions that can’t be used generically with other variables or arguments since they rely on a single global variable
  • Lack of thread safety when using global variables

Contrast the previous example with the following, which explicitly returns a value:

Much better! You avoid all potential issues with global variables, and by requiring an argument, you make your function clearer.

Despite being neither a pass-by-reference language nor a pass-by-value language, Python suffers no shortcomings in that regard. Its flexibility more than meets the challenge.

You’ve already touched on returning values from the function and reassigning them to a variable. For functions that operate on a single value, returning the value is much clearer than using a reference. Furthermore, since Python already uses pointers behind the scenes, there would be no additional performance benefits even if it were able to pass arguments by reference.

Aim to write single-purpose functions that return one value, then (re)assign that value to variables, as in the following example:

Returning and assigning values also makes your intention explicit and your code easier to understand and test.

For functions that operate on multiple values, you’ve already seen that Python is capable of returning a tuple of values . You even surpassed the elegance of Int32.TryParse() in C# thanks to Python’s flexibility!

If you need to operate on multiple values, then you can write single-purpose functions that return multiple values, then (re)assign those values to variables. Here’s an example:

When calling a function that returns multiple values, you can assign multiple variables at the same time.

Object attributes have their own place in Python’s assignment strategy. Python’s language reference for assignment statements states that if the target is an object’s attribute that supports assignment, then the object will be asked to perform the assignment on that attribute. If you pass the object as an argument to a function, then its attributes can be modified in place.

Write functions that accept objects with attributes, then operate directly on those attributes, as in the following example:

Note that square() needs to be written to operate directly on an attribute, which will be modified without the need to reassign a return value.

It’s worth repeating that you should make sure the attribute supports assignment! Here’s the same example with namedtuple , whose attributes are read-only:

Attempts to modify attributes that don’t allow modification result in an AttributeError .

Additionally, you should be mindful of class attributes . They will remain unchanged, and an instance attribute will be created and modified:

Since class attributes remain unchanged when modified through a class instance, you’ll need to remember to reference the instance attribute.

Dictionaries in Python are a different object type than all other built-in types. They’re referred to as mapping types . Python’s documentation on mapping types provides some insight into the term:

A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. ( Source )

This tutorial doesn’t cover how to implement a custom mapping type, but you can replicate pass by reference using the humble dictionary. Here’s an example using a function that operates directly on dictionary elements:

Since you’re reassigning a value to a dictionary key, operating on dictionary elements is still a form of assignment. With dictionaries, you get the added practicality of accessing the modified value through the same dictionary object.

While lists aren’t mapping types, you can use them in a similar way to dictionaries because of two important characteristics: subscriptability and mutability . These characteristics are worthy of a little more explanation, but let’s first take a look at best practices for mimicking pass by reference using Python lists.

To replicate pass by reference using lists, write a function that operates directly on list elements:

Since you’re reassigning a value to an element within the list, operating on list elements is still a form of assignment. Similar to dictionaries, lists allow you to access the modified value through the same list object.

Now let’s explore subscriptability. An object is subscriptable when a subset of its structure can be accessed by index positions:

Lists, tuples, and strings are subscriptable, but sets are not. Attempting to access an element of an object that isn’t subscriptable will raise a TypeError .

Mutability is a broader topic requiring additional exploration and documentation reference . To keep things short, an object is mutable if its structure can be changed in place rather than requiring reassignment:

Lists and sets are mutable, as are dictionaries and other mapping types. Strings and tuples are not mutable. Attempting to modify an element of an immutable object will raise a TypeError .

Python works differently from languages that support passing arguments by reference or by value. Function arguments become local variables assigned to each value that was passed to the function. But this doesn’t prevent you from achieving the same results you’d expect when passing arguments by reference in other languages.

In this tutorial, you learned:

  • How Python handles assigning values to variables
  • How function arguments are passed by assignment in Python
  • Why returning values is a best practice for replicating pass by reference
  • How to use attributes , dictionaries , and lists as alternative best practices

You also learned some additional best practices for replicating pass-by-reference constructs in Python. You can use this knowledge to implement patterns that have traditionally required support for passing by reference.

To continue your Python journey, I encourage you to dive deeper into some of the related topics that you’ve encountered here, such as mutability , assignment expressions , and Python namespaces and scope .

Stay curious, and see you next time!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Marius Mogyorosi

Marius Mogyorosi

Marius is a tinkerer who loves using Python for creative projects within and beyond the software security field.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices python

Recommended Video Course: Pass by Reference in Python: Best Practices

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

5 Thoughts On Python Mastery

🔒 No spam. We take your privacy seriously.

assignment by value or reference

Naveen Karippai

Quick Tip: How JavaScript References Work

Share this article

A computer screen with blue binary data scrolling like the Matrix

The Bottom Line on JavaScript References

Quick example of assign-by-value:, quick example of assign-by-reference:, how to create a new reference, how references work when values are passed as function parameters, how to change the original value in a compound variable, passed as a function argument via a javascript reference, how to store a compound value through assign-by-value, how to store a scalar primitive value through assign-by-reference, frequently asked questions (faqs) about javascript references.

TL;DR: There are NO pointers in JavaScript and references work differently from what we would normally see in most other popular programming languages. In JavaScript, it’s just NOT possible to have a reference from one variable to another variable. And, only compound values (e.g.. Object or Array) can be assigned by reference.

Morpheus: What if I told you, you can write references in JavaScript?

The following terms are used throughout the article:

  • scalar – a singe value or unit of data (e.g. integer, boolean , string)
  • compound – comprised of multiple values (e.g. array, object, set)
  • primitive – a direct value, as opposed to a reference to something that contains the real value.

JavaScript’s scalar types are primitives, but some languages, such as Ruby, have scalar reference types. Note that in JavaScript, the scalar primitive values are immutable while compound values are mutable.

  • The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference.
  • On variable assignment, the scalar primitive values (Number, String, Boolean, undefined, null, Symbol) are assigned-by-value and compound values are assigned-by-reference.
  • The references in JavaScript only point at contained values and NOT at other variables, or references.
  • In JavaScript, scalar primitive values are immutable and compound values are mutable.

In the code snippet below, we are assigning a scalar primitive value (a number) to a variable and thus assign-by-value applies here. Firstly, the variable batman is initialized and when the variable superman is assigned with the value stored in batman , it creates a new copy of the value and stores it. When the variable superman is modified, batman is left unaffected, as they point to distinct values.

Assign-by-value example

In the code snippet below, we are assigning a compound value (an array) to a variable and thus assign-by-reference applies here. The variables flash and quicksilver are references to the same value (aka shared value). The references will point to the updated value when the shared value is modified .

Assign-by-reference example

When the compound value in a variable is reassigned, a new reference is created. In JavaScript, unlike in most other popular programming languages, the references are pointers to values stored in variables and NOT pointers to other variables, or references.

Creating a new reference

In the code snippet below, the variable magneto is a compound value (an Array), thus it is assigned to variable (function argument) x as a reference.

The Array.prototype.push method invoked inside the IIFE mutates the value in the variable magneto via a JavaScript reference. But, the reassignment of variable x creates a new reference and further modifications to it do NOT affect the reference to the variable magneto .

The solution here would be to modify the existing compound value that the reference is pointing to. In the code snippet below, variable wolverine is a compound value (an Array) and, on IIFE invocation, the variable (function argument) x is assigned by reference.

The Array.prototype.length property can be used to create an empty array by setting its value to 0 . Thus, the variable wolverine is changed to the new value set in variable x via a JavaScript reference.

The solution here would be to make a manual copy of the compound value and then assign the copied value to a variable. Therefore, the reference of assigned value does NOT point back to the original value.

The recommended approach to create a (shallow) copy of the compound value (Array object) is to invoke Array.prototype.slice method on it with no arguments passed.

Diagram4

The solution here would be to wrap scalar primitive value in a compound value (i.e. an Object or Array) as its property value. Thus, it can be assigned-by-reference. In the code snippet below, scalar primitive value in variable speed is set as a property on object flash . Therefore, it is assigned-by-reference on IIFE invocation to variable (function argument) x .

Neo stopping bullets in mid-air. Caption: References in JavaScript

A good understanding of references in JavaScript can help developers to avoid many common mistakes and write better code.

Happy coding!!

What is the difference between primitive and reference values in JavaScript?

In JavaScript, data types are divided into two categories: primitive (or basic) types and reference types. Primitive types include Number, String, Boolean, Null, Undefined, and Symbol. These types store actual values. For example, if you assign a number to a variable, JavaScript stores the actual number, not a reference to it. On the other hand, reference types include Objects, Arrays, and Functions. These types do not store the actual value. Instead, they store a reference or a pointer to the location in memory where the value is stored. This difference is crucial when you’re performing operations like comparison or copying variables.

How does JavaScript handle reference types when assigning them to a new variable?

When you assign a reference type (like an object or an array) to a new variable, JavaScript does not create a new copy of that value. Instead, it creates a new reference to the same memory location. This means that if you modify the new variable, the original variable will also be affected because they both point to the same data.

What is the concept of pass-by-reference in JavaScript?

In JavaScript, when you pass a reference type (like an object or an array) to a function, it is passed by reference. This means that the function does not receive a new copy of the value. Instead, it gets a reference to the original value. Therefore, if the function modifies the value, the change will be reflected outside the function as well.

How can I clone or copy an object without affecting the original object in JavaScript?

To clone or copy an object without affecting the original object, you can use methods like Object.assign() or the spread operator (…). These methods create a new object with the same properties as the original object, but they do not create a reference to the original object. Therefore, changes to the new object will not affect the original object.

What is the difference between shallow copy and deep copy in JavaScript?

A shallow copy creates a new object and copies over the values of the original object’s properties. However, if the property value is a reference type, it copies the reference, not the actual value. Therefore, changes to the nested objects will affect both the original and the copied object. On the other hand, a deep copy creates a new object and recursively copies all the values of the original object’s properties, including nested objects. Therefore, changes to the copied object will not affect the original object. You can create a deep copy using methods like JSON.parse(JSON.stringify(object)).

How does the ‘this’ keyword work in JavaScript?

The ‘this’ keyword in JavaScript refers to the object that the function is a property of. The value of ‘this’ is determined at the time of function invocation. However, the behavior of ‘this’ can be confusing when it is used inside callbacks or event handlers, as it may not point to the object you expect.

How can I change the context of ‘this’ in a function?

You can change the context of ‘this’ in a function using methods like call(), apply(), or bind(). These methods allow you to invoke a function with a specified ‘this’ value and arguments.

What is a closure in JavaScript?

A closure in JavaScript is a function that has access to its own scope, the outer function’s scope, and the global scope. Closures are created every time a function is created, at function creation time. They are commonly used to create private variables or functions.

How does garbage collection work in JavaScript?

Garbage collection in JavaScript is an automatic memory management process. When an object is no longer reachable or needed, the JavaScript engine’s garbage collector frees up the memory occupied by that object. Reachability is determined by whether there is a reference to the object.

What is the difference between ‘==’ and ‘===’ in JavaScript?

The ‘==’ operator in JavaScript performs type coercion and then checks for equality. This means that it converts the operands to a common type before comparison. On the other hand, the ‘===’ operator checks for both value and type equality, without performing type coercion. Therefore, ‘===’ is often recommended for equality checks to avoid unexpected results due to type coercion.

JavaScript; Elm; Python Developer

SitePoint Premium

DEV Community

DEV Community

iAmGjert

Posted on Feb 18, 2022

Copy by Value vs Reference

sample variable

Copy by Value When working with primitive data types (numbers, strings, Booleans, null, and undefined) your variables will be making a copy of the value they're being assigned and represent that specific copy of the value. Any changes to the original data will not effect the copy that was made and stored in the variable we've created. Vice versa, these values stored into our variable can be manipulated without any changes to the original data.

value copies

In the image above, b is being assigned the value stored in the a variable. Since the a variable is storing a primitive data type b is assigned a copy of that value. Any changes made to a later on will not effect b 's value. a === 1 //true b === 1 //true

Copy by Reference When working with complex data types (Objects, arrays, functions) your variables will not make a copy of the value they're being assigned to, but instead will make a reference to that data. Any manipulation of our variable will effect the original data since our variable is just a reference to the original data. Similarly, any changes to the original data will effect our variable as well.

In the code above, the a variable has been assigned to an object with two properties. Just under that, we've assigned the b variable to the a variable. When the b variable is assigned here, it will be assigned a reference to the same object the a variable is already assigned to. Any changes to the b variable will effect the original data stored in the a variable. b.color = 'orange' Since both variables point to the same object, the color of the object both variables point to will be assigned to 'orange'.

by reference

Top comments (14)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

parenttobias profile image

  • Location Northeastern Connecticut
  • Education Some, yes. Never enough.
  • Work Full-stack hack at Self-employed
  • Joined May 1, 2020

The issue with the whole "pass by value" vs "pass by reference" thing is, javascript doesn't really do either . Well it does both . Well it does...

Javascript is consistent, both primitives and non-primitives work the same way. A string is passed the same way as an object, in large part. But the concepts of value or reference is fuzzy here, because any references are implicit , not explicit . We don't have pointers, so we aren't sharing a reference - but it seems we do, as arrays and objects are mutable from either side.

I think the best description I've seen for javascript's way of passing is Pass by share . When we pass something into a function, be it primitive or not, we are sharing the reference to that thing. We can't act on the reference, we can only follow it. In the case of primitive data types the value we reach is immutable , so any transformation becomes a new thing. But with non-primitive types, where mutation is possible, a shared reference becomes a little more problematic.

I've always seen the "Is javascript pass by reference or pass by value?" to be a trick question, for which there is no clean answer. It's the kind of a question, in an interview, intended to be wrong.

Edit for completeness: When I mentioned above "in large part*, it's because, internally, javascript does funky stuff with smallInt values, from what I've read. Rather than the variable referencing a lookup table, which referrences memory locations, which reference values? From what I've read, smallInt values are the only ones stored directly in the lookup table, and thus the only ones pass by value. What that means? Absolutely no idea. Still trying to test that, and see if it's relevant.

aminmansuri profile image

  • Joined Aug 26, 2018

The true way to know if you're passing by reference in a language is this:

func f(ref val) { val = newVal; }

x = something f(x)

If x is now equal to newVal then your language supports passing by reference (ex: in Pascal this works with var, or in C++ & notation). If x is still equal to "something" then I'm afraid you don't have true pass by reference.

guillep2k profile image

  • Location Madrid
  • Joined Oct 11, 2019

That's a different discussion. The article is about assignments, not function calling.

And that's why I suggest a different verb, pass by share . We are sharing that reference in an assignment to another variable, rather than passing the value itself. However the reference is tied to the immutable value, and not to the variable.

Javascript is weird, but once you grok, it actually makes a lot of sense.

jkhaui profile image

  • Location Melbourne
  • Education Swinburne University of Technology
  • Work Software Developer at Loup.
  • Joined Oct 20, 2018

Nice article. For completeness’ sake and clarity, you might want to add ‘Symbol’ and ‘BigInt’ for the full list of JS primitive types.

Might also wanna let readers know that arrays and functions in JS are technically objects too :)

sarveshprajapati profile image

  • Location India
  • Work Content Creator @ WithinBracket
  • Joined Sep 23, 2020

Great article though... Would be better to discuss a bit about heap . Either way... great content

danwalsh profile image

  • Location Melbourne, Australia
  • Work Web Developer / Designer
  • Joined Dec 11, 2020

Great read! 👏

It's worth mentioning that if you're intending to make a copy of a non-primitive, you can do so using the spread operator:

I find it particularly useful when making changes to the state object in my React useReducer() logic.

marcio199226 profile image

  • Location milan
  • Work Full stack develper
  • Joined Nov 11, 2020

Watch out that objects copied by destructuring it will be a shallow copy so any nested objects will still link to their "reference"

The same happens to arrays as well

Great point! It clearly illustrates that you need to pick the method for your specific needs: by reference, shallow copy and deep copy. Each has its pros, cons and use cases.

One could argue that every variable holds a reference, at least in abstraction. Using let a = 1 doesn't contradict this, because one can say it's the object 1 that's being assigned. This pseudo object has no properties and can not be manipulated, but can be assigned to other variables, just like any bonafide object. If we then say a = 2 , we'd be changing the reference a is pointing to, rather than changing the actual number. I know this is entirely semantics, and that the actual implementation does classify values as different from references internally, but making that distinction while learning the language seems unnecessary. I hope this makes sense.

jawwad profile image

  • Location Bhola,Bangladesh
  • Work Frontend Developer
  • Joined Nov 14, 2020

This is very informative in a short lengh.

ash_bergs profile image

  • Location Grand Rapids, MI
  • Work Full Stack Engineer
  • Joined Dec 7, 2020

I like this add-on! I know this caveat to strings has tripped me up more than once.

omarpervez profile image

  • Location Noakhali, Bangladesh.
  • Education Noakhali Science and Technology University
  • Work Front-end Web Developer at PPH
  • Joined Dec 2, 2021

Excellent blog. Thank you for sharing your ideas with us😊

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

mikeyoung44 profile image

Tora: Breakthrough Video AI Captures Motion Like Never Before

Mike Young - Aug 4

jaimaldullat profile image

10 JavaScript Hacks That Will Make You Say “Where Have You Been All My Life?

Jaimal Dullat - Aug 10

dhruvjoshi9 profile image

Why Python Developers losing jobs? Tips To Survive

Dhruv Joshi - Aug 10

BRIGHT: New Text Retrieval Benchmark Requiring Intensive Reasoning to Identify Relevant Documents

Mike Young - Jul 21

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Artificial Intelligence
  • Generative AI
  • Cloud Computing
  • Data Management
  • Emerging Technology
  • Technology Industry
  • Software Development
  • Microsoft .NET
  • Development Tools
  • Open Source
  • Programming Languages
  • Enterprise Buyer’s Guides
  • Newsletters
  • Foundry Careers
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Copyright Notice
  • Member Preferences
  • About AdChoices
  • E-commerce Affiliate Relationships
  • Your California Privacy Rights

Our Network

  • Computerworld
  • Network World

rafael_del nero

Does Java pass by reference or pass by value?

You might know that java passes by value, but it helps to understand why. here's what happens when you pass mutable and immutable object references in java..

Scoring the winning points at a basketball game

Many programming languages allow passing objects by reference or by value. In Java, we can only pass object parameters by value. This imposes limits and also raises questions. For instance, if the parameter value is changed in the method, what happens to the value following method execution? You may also wonder how Java manages object values in the memory heap. This article helps you resolve these and other common questions about object references in Java.

Passing object references in Java

In this article you’ll learn the difference between passing by reference and passing by value in Java and how to pass Java object references:

‘Pass by reference’ and ‘pass by value’ defined

Java object references are passed by value, passing primitive types in java, passing immutable object references in java, passing mutable object references in java.

  • What to avoid when passing object references
  • What to remember about passing object references

Pass by reference  means we pass the location in memory where the variable’s value is stored and pass by value means we pass a copy of the variable’s actual value. It’s a bit more complicated than that, of course, but this definition is a good starting point.

  • Passing by value means we pass a copy of the value.
  • Passing by reference means we pass the real reference to the variable in memory.

All object references in Java are passed by value. This means that a copy of the value will be passed to a method. The tricky part is that passing a copy of the value changes the real value of the object. This example should help you understand why:

What do you think the simpson.name will be after the transformIntoHomer method is executed?

In this case, it will be Homer! The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

If you’re still not sure how this works, consider the following diagram:

Flow diagram of object references in Java

Like object types, primitive types are also passed by value. Can you guess what will happen to the primitive types in the following code example?

If you determined that the value would change to 30, you are correct. It’s 30 because (again) Java passes object parameters by value. The number 30 is just a copy of the value, not the real value. Primitive types are allocated in the stack memory, so only the local value will be changed. In this case, there is no object reference.

What if we did the same test with an immutable String object? Notice what happens when we change the value of a String :

What do you think the output will be? If you guessed “” then congratulations! That happens because a String object is immutable , which means that the fields inside the String are final and can’t be changed.

Making the String class immutable gives us better control over one of Java’s most used objects. If the value of a String could be changed, it would create many bugs. Note, also, that we are not changing an attribute of the String class; instead, we’re simply assigning a new String value to it. In this case, the “Homer” value will be passed to name in the changeToHomer method. The String “Homer” will be eligible to be garbage collected as soon as the changeToHomer method completes execution. Even though the object can’t be changed, the local variable will be.

Unlike String , most objects in the JDK are mutable, like the StringBuilder class. The example below is similar to the previous one, but features StringBuilder rather than String :

Can you guess the output for this example? In this case, because we’re working with a mutable object, the output will be “Homer Simpson.” You could expect the same behavior from any other mutable object in Java.

Summary of what you’ve learned

You’ve learned that Java objects are passed by value, meaning that a copy of the value is passed . Just remember that the copied value points to a real object in the Java memory heap. Also, remember that passing by value changes the value of the real object.

What to avoid when passing Java object references

  • Don’t try to change an immutable value by reference.
  • Don’t try to change a primitive variable by reference.
  • Don’t expect the real object won’t change when you change a mutable object parameter in a method (it will change).

What to remember about passing Java object references

  • Java always passes parameter variables by value.
  • Object variables in Java always point to the real object in the memory heap.
  • A mutable object’s value can be changed when it is passed to a method.
  • An immutable object’s value cannot be changed, even if it is passed a new value.

Test what you’ve learned about object references

Now, let’s test what you’ve learned about object references. In the code example below, you see the immutable String and the mutable StringBuilder class. Each is being passed as a parameter to a method. Knowing that Java only passes by value, what do you believe will be the output once the main method from this class is executed?

Here are the options, check the end of the article for the answer.

A : Warrior=null Weapon=null B : Warrior=Dragon Weapon=Dragon C : Warrior=Dragon Knight Weapon=Dragon Sword D : Warrior=Dragon Knight Weapon=Sword

Solving the challenge

The first parameter in the above example is the warriorProfession variable, which is a mutable object. The second parameter, weapon, is an immutable String :

At the first line of this method, we append the Knight value to the warriorProfession variable. Remember that warriorProfession is a mutable object; therefore the real object will be changed, and the value from it will be “Dragon Knight.”

In the second instruction, the immutable local String variable will be changed to “Dragon Sword.” The real object will never be changed, however, since String is immutable and its attributes are final:

Finally, we pass null to the variables here, but not to the objects. The objects will remain the same as long as they are still accessible externally—in this case through the main method. And, although the local variables will be null, nothing will happen to the objects:

From this we can conclude that the final values from our mutable StringBuilder and immutable String will be:

The only value that changed in the changeWarriorClass method was warriorProfession , because it’s a mutable StringBuilder object. Note that warriorWeapon did not change because it’s an immutable String object.

The correct output from our Challenger code would be:

D : Warrior=Dragon Knight Weapon=Sword .

Video challenge! Debugging object references in Java

Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video, you can follow along while I debug and explain object references in Java.

Learn more about Java

  • Get more quick code tips: Read all of Rafael’s articles in the InfoWorld Java Challengers series.
  • Check out more videos in Rafael’s Java Challengers video playlist .
  • Find even more Java Challengers on Rafael’s Java Challengers blog and in his book, with more than 70 code challenges .

Related content

Why i don’t buy apple products, tauri 2.0 moves core functionality to plugins, 5 things great data science product managers do, practical strategies for mitigating api security risks.

rafael_del nero

Rafael del Nero is a Java Champion and Oracle Ace, creator of the Java Challengers initiative, and a quiz master in the Oracle Dev Gym. Rafael is the author of "Java Challengers" and "Golden Lessons." He believes there are many techniques involved in creating high-quality software that developers are often unaware of. His purpose is to help Java developers use better programming practices to code quality software for stress-free projects with fewer bugs.

More from this author

Thread behavior in the jvm, polymorphism and inheritance in java, java inheritance vs. composition: how to choose, sorting java objects with comparable and comparator, comparing java objects with equals() and hashcode(), replace calendar with localdate in java programs, shallow and deep copy: two ways to copy objects in java, when to use abstract classes vs. interfaces in java, most popular authors.

assignment by value or reference

Show me more

Remember quantum computing in the cloud.

Image

iPaaS in an AI-driven world

Image

Google Cloud adds 3 new Apache Airflow operators to Vertex AI

Image

How to use the watch command

Image

How to use dbm to stash data quickly in Python

Image

How to auto-generate Python type hints with Monkeytype

Image

  • Sign In / Suggest an Article

Current ISO C++ status

Upcoming ISO C++ meetings

Upcoming C++ conferences

Compiler conformance status

ISO C++ committee meeting

June 24-29, St. Louis, MO, USA

July 2-5, Folkestone, Kent, UK

value vs ref semantics

Reference and value semantics, what is value and/or reference semantics, and which is best in c++.

With reference semantics, assignment is a pointer-copy (i.e., a reference ). Value (or “copy”) semantics mean assignment copies the value, not just the pointer. C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the default (and most common) choice is to copy the value.

Pros of reference semantics: flexibility and dynamic binding (you get dynamic binding in C++ only when you pass by pointer or pass by reference, not when you pass by value).

Pros of value semantics: speed. “Speed” seems like an odd benefit for a feature that requires an object (vs. a pointer) to be copied, but the fact of the matter is that one usually accesses an object more than one copies the object, so the cost of the occasional copies is (usually) more than offset by the benefit of having an actual object rather than a pointer to an object.

There are three cases when you have an actual object as opposed to a pointer to an object: local objects, global/ static objects, and fully contained member objects in a class. The most important of these is the last (“composition”).

More info about copy-vs-reference semantics is given in the next FAQs. Please read them all to get a balanced perspective. The first few have intentionally been slanted toward value semantics, so if you only read the first few of the following FAQs, you’ll get a warped perspective.

Assignment has other issues (e.g., shallow vs. deep copy) which are not covered here.

What is “ virtual data,” and how-can / why-would I use it in C++?

virtual data allows a derived class to change the exact class of a base class’s member object. virtual data isn’t strictly “supported” by C++, however it can be simulated in C++. It ain’t pretty, but it works.

To simulate virtual data in C++, the base class must have a pointer to the member object, and the derived class must provide a new object to be pointed to by the base class’s pointer. The base class would also have one or more normal constructors that provide their own referent (again via new ), and the base class’s destructor would delete the referent.

For example, class Stack might have an Array member object (using a pointer), and derived class StretchableStack might override the base class member data from Array to StretchableArray . For this to work, StretchableArray would have to inherit from Array , so Stack would have an Array* . Stack ’s normal constructors would initialize this Array* with a new Array , but Stack would also have a (possibly protected ) constructor that would accept an Array* from a derived class. StretchableStack ’s constructor would provide a new StretchableArray to this special constructor.

  • Easier implementation of StretchableStack (most of the code is inherited)
  • Users can pass a StretchableStack as a kind-of Stack
  • Adds an extra layer of indirection to access the Array
  • Adds some extra freestore allocation overhead (both new and delete )
  • Adds some extra dynamic binding overhead (reason given in next FAQ)

In other words, we succeeded at making our job easier as the implementer of StretchableStack , but all our users pay for it . Unfortunately the extra overhead was imposed on both users of StretchableStack and on users of Stack .

Please read the rest of this section. ( You will not get a balanced perspective without the others. )

What’s the difference between virtual data and dynamic data?

The easiest way to see the distinction is by an analogy with virtual functions : A virtual member function means the declaration (signature) must stay the same in derived classes, but the definition (body) can be overridden. The overriddenness of an inherited member function is a static property of the derived class; it doesn’t change dynamically throughout the life of any particular object, nor is it possible for distinct objects of the derived class to have distinct definitions of the member function.

Now go back and re-read the previous paragraph, but make these substitutions:

  • “member function” → “member object”
  • “signature” → “type”
  • “body” → “exact class”

After this, you’ll have a working definition of virtual data.

Another way to look at this is to distinguish “per-object” member functions from “dynamic” member functions. A “per-object” member function is a member function that is potentially different in any given instance of an object, and could be implemented by burying a function pointer in the object; this pointer could be const , since the pointer will never be changed throughout the object’s life. A “dynamic” member function is a member function that will change dynamically over time; this could also be implemented by a function pointer, but the function pointer would not be const.

Extending the analogy, this gives us three distinct concepts for data members:

  • virtual data: the definition ( class ) of the member object is overridable in derived classes provided its declaration (“type”) remains the same, and this overriddenness is a static property of the derived class
  • per-object-data: any given object of a class can instantiate a different conformal (same type) member object upon initialization (usually a “wrapper” object), and the exact class of the member object is a static property of the object that wraps it
  • dynamic-data: the member object’s exact class can change dynamically over time

The reason they all look so much the same is that none of this is “supported” in C++. It’s all merely “allowed,” and in this case, the mechanism for faking each of these is the same: a pointer to a (probably abstract) base class. In a language that made these “first class” abstraction mechanisms, the difference would be more striking, since they’d each have a different syntactic variant.

Should I normally use pointers to freestore allocated objects for my data members, or should I use “composition”?

Composition.

Your member objects should normally be “contained” in the composite object (but not always; “wrapper” objects are a good example of where you want a pointer/reference; also the N-to-1-uses-a relationship needs something like a pointer/reference).

There are three reasons why fully contained member objects (“composition”) has better performance than pointers to freestore-allocated member objects:

  • Extra layer of indirection every time you need to access the member object
  • Extra freestore allocations ( new in constructor, delete in destructor)
  • Extra dynamic binding (reason given below)

What are relative costs of the 3 performance hits associated with allocating member objects from the freestore?

The three performance hits are enumerated in the previous FAQ:

  • By itself, an extra layer of indirection is small potatoes
  • Freestore allocations can be a performance issue (the performance of the typical implementation of malloc() degrades when there are many allocations; OO software can easily become “freestore bound” unless you’re careful)
  • The extra dynamic binding comes from having a pointer rather than an object. Whenever the C++ compiler can know an object’s exact class, virtual function calls can be statically bound, which allows inlining. Inlining allows zillions (would you believe half a dozen :-) optimization opportunities such as procedural integration, register lifetime issues, etc. The C++ compiler can know an object’s exact class in three circumstances: local variables, global/ static variables, and fully-contained member objects

Thus fully-contained member objects allow significant optimizations that wouldn’t be possible under the “member objects-by-pointer” approach. This is the main reason that languages which enforce reference-semantics have “inherent” performance challenges.

Note: Please read the next three FAQs to get a balanced perspective!

Are “ inline virtual ” member functions ever actually “inlined”?

Occasionally…

When the object is referenced via a pointer or a reference, a call to a virtual function generally cannot be inlined, since the call must be resolved dynamically. Reason: the compiler can’t know which actual code to call until run-time (i.e., dynamically), since the code may be from a derived class that was created after the caller was compiled.

Therefore the only time an inline virtual call can be inlined is when the compiler knows the “exact class” of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/ static object, or a fully contained object inside a composite. This situation can sometimes happen even with a pointer or reference, for example when functions get inlined, access through a pointer or reference may become direct access on the object.

Note that the difference between inlining and non-inlining is normally much more significant than the difference between a regular function call and a virtual function call. For example, the difference between a regular function call and a virtual function call is often just two extra memory references, but the difference between an inline function and a non- inline function can be as much as an order of magnitude (for zillions of calls to insignificant member functions, loss of inlining virtual functions can result in 25X speed degradation! [Doug Lea, “Customization in C++,” proc Usenix C++ 1990]).

A practical consequence of this insight: don’t get bogged down in the endless debates (or sales tactics!) of compiler/language vendors who compare the cost of a virtual function call on their language/compiler with the same on another language/compiler. Such comparisons are largely meaningless when compared with the ability of the language/compiler to “ inline expand” member function calls. I.e., many language implementation vendors make a big stink about how good their dispatch strategy is, but if these implementations don’t inline member function calls, the overall system performance would be poor, since it is inlining — not dispatching— that has the greatest performance impact.

Here is an example of where virtual calls can be inlined even through a reference. The following code is all in the same translation unit, or otherwise organized such that the optimizer can see all of this code at once.

The compiler is free to transform main as follows:

It is now able to inline the virtual function calls.

Note: Please read the next two FAQs to see the other side of this coin!

Sounds like I should never use reference semantics, right?

Reference semantics are A Good Thing. We can’t live without pointers. We just don’t want our software to be One Gigantic Rats Nest Of Pointers. In C++, you can pick and choose where you want reference semantics (pointers/references) and where you’d like value semantics (where objects physically contain other objects etc). In a large system, there should be a balance. However if you implement absolutely everything as a pointer, you’ll get enormous speed hits.

Objects near the problem skin are larger than higher level objects. The identity of these “problem space” abstractions is usually more important than their “value.” Thus reference semantics should be used for problem-space objects.

Note that these problem space objects are normally at a higher level of abstraction than the solution space objects, so the problem space objects normally have a relatively lower frequency of interaction. Therefore C++ gives us an ideal situation: we choose reference semantics for objects that need unique identity or that are too large to copy, and we can choose value semantics for the others. Thus the highest frequency objects will end up with value semantics, since we install flexibility where it doesn’t hurt us (only), and we install performance where we need it most!

These are some of the many issues that come into play with real OO design. OO/C++ mastery takes time and high quality training. If you want a powerful tool, you’ve got to invest.

Don’t stop now! Read the next FAQ too!!

Does the poor performance of reference semantics mean I should pass-by-value?

The previous FAQ were talking about member objects, not parameters. Generally, objects that are part of an inheritance hierarchy should be passed by reference or by pointer, not by value, since only then do you get the (desired) dynamic binding (pass-by-value doesn’t mix with inheritance, since larger derived class objects get sliced when passed by value as a base class object).

Unless compelling reasons are given to the contrary, member objects should be by value and parameters should be by reference. The discussion in the previous few FAQs indicates some of the “compelling reasons” for when member objects should be by reference.

Please Login to submit a recommendation.

If you don’t have an account, you can register for free.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assignment operators (C# reference)

  • 11 contributors

The assignment operator = assigns the value of its right-hand operand to a variable, a property , or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or implicitly convertible to it.

The assignment operator = is right-associative, that is, an expression of the form

is evaluated as

The following example demonstrates the usage of the assignment operator with a local variable, a property, and an indexer element as its left-hand operand:

The left-hand operand of an assignment receives the value of the right-hand operand. When the operands are of value types , assignment copies the contents of the right-hand operand. When the operands are of reference types , assignment copies the reference to the object.

This is called value assignment : the value is assigned.

ref assignment

Ref assignment = ref makes its left-hand operand an alias to the right-hand operand, as the following example demonstrates:

In the preceding example, the local reference variable arrayElement is initialized as an alias to the first array element. Then, it's ref reassigned to refer to the last array element. As it's an alias, when you update its value with an ordinary assignment operator = , the corresponding array element is also updated.

The left-hand operand of ref assignment can be a local reference variable , a ref field , and a ref , out , or in method parameter. Both operands must be of the same type.

Compound assignment

For a binary operator op , a compound assignment expression of the form

is equivalent to

except that x is only evaluated once.

Compound assignment is supported by arithmetic , Boolean logical , and bitwise logical and shift operators.

Null-coalescing assignment

You can use the null-coalescing assignment operator ??= to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . For more information, see the ?? and ??= operators article.

Operator overloadability

A user-defined type can't overload the assignment operator. However, a user-defined type can define an implicit conversion to another type. That way, the value of a user-defined type can be assigned to a variable, a property, or an indexer element of another type. For more information, see User-defined conversion operators .

A user-defined type can't explicitly overload a compound assignment operator. However, if a user-defined type overloads a binary operator op , the op= operator, if it exists, is also implicitly overloaded.

C# language specification

For more information, see the Assignment operators section of the C# language specification .

  • C# operators and expressions
  • ref keyword
  • Use compound assignment (style rules IDE0054 and IDE0074)

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Why Assignment Operator Overloading Must Return Reference?

Operator overloading in C++ allows us to define custom behaviors for operators when applied to user-defined types. One of the most commonly overloaded operators is the assignment operator (=), which is used to assign the value of one object to another. However, when overloading the assignment operator, it’s important to ensure that it returns a reference to the object being assigned. But why is this necessary?

In this article, we will learn why the assignment operator must return a reference in C++ when overloading, and what could go wrong if it doesn’t.

Why Must the Assignment Operator Return a Reference?

When overloading the assignment operator in C++ , it’s important that it returns a reference to the object being assigned. There are several key reasons for this:

1. Chaining of Assignment Operations

In C++, assignment operations can be chained together.

For example:

To support this chaining, the assignment operator must return a reference to the object being assigned. This allows the operation b = c to return b, enabling a = b to work as expected.

2. Consistency with Built-in Types

For built-in types, the assignment operator in C++ returns a reference to the left-hand operand. To maintain consistency and intuitive behavior for user-defined types, overloaded assignment operators should also return a reference.

3. Avoiding Unnecessary Object Copies

If the assignment operator returned an object by value instead of by reference, it would result in the creation of a temporary object, which is immediately discarded. This unnecessary copying is inefficient and could lead to performance issues, especially for large objects or objects managing dynamic resources.

C++ Program to Demonstrate Properly Overloading the Assignment Operator

The below example demonstartes how to properly overload the assignment operator in C++.

What Happens if Assignment Operator Does Not Return a Reference?

If we overload the assignment operator and return by value instead of by reference, several issues could arise:

  • Chained assignments like a = b = c; would not work correctly.
  • Returning by value would create temporary objects, leading to inefficiencies.
  • The overloaded assignment operator would behave differently from the built-in assignment operator, which could confuse others of our class.

In C++, when overloading the assignment operator, we must return a reference to the current object ( *this ) as it allows for assignment chaining, maintains consistency with built-in types, and avoids unnecessary object copying. By following these best practice, we can ensure that our overloaded operators are efficient, intuitive, and behave as expected, making our C++ programs more robust and maintainable.

author

Please Login to comment...

Similar reads.

  • C++-Operator Overloading

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

C# Reference type assignment VS value type assignment

I understand the theoretical concept that assigning one reference type variable to another, only the reference is copied, not the object. assigning one value type variable to another, the object is copied. But I cannot spot the different in the code. would someone kindly point out the difference between the following two code blocks? Thank you!

REFERENCE TYPE ASSIGNMENT

VALUE TYPE ASSIGNMENT

ValidfroM's user avatar

  • 2 The output is as it should be. So, what is the question? –  shahkalpesh Commented Aug 2, 2009 at 19:54
  • As per the example, it is only the 3rd point where it is different. Changing one of the references will affect other instances referring to it. It won't be the case in value type. –  shahkalpesh Commented Aug 2, 2009 at 19:56
  • This would be a lot clearer if you'd used the same terms in both blocks of code. –  Tim Long Commented Aug 2, 2009 at 20:09

6 Answers 6

Well, the obvious difference is that with the class example, it appears both joe and bob changed in the last part there, to the same value.

In the struct example, they keep their separate values, simply because each variable is a whole struct value by itself, not just a reference to a common object in memory somewhere.

The main code-wise difference being the type you use, class or struct , this dictates whether you're creating a reference type or a value type.

Lasse V. Karlsen's user avatar

  • That's it? Which is which!?! At least say that much or offer a link... ._. –  Paul-Sebastian Manole Commented Jan 25, 2013 at 12:20

One is a structure and the other is a class. This seems like an overly complicated example involving more than just value and reference differences but the differences between classes and structs as well.

When one struct is assigned to another a copy is made. When one class is assigned to another only the reference changes.

Spencer Ruport's user avatar

//Reference Type

pratik's user avatar

The first code snippet contains Employee which is a class and in the second one, Employee is a struct

Victor Hurdugaci's user avatar

To see the difference more clearly, try something like

// assign joe reference value to bob variable

And do something similar in the reference-type example.

You will be able to demonstrate that in the second examples there are two different instances of Height, while in the first example there is only one (shared) instance of Employee.

Henk Holterman's user avatar

On my system, those two code blocks produce the following output:

Original Employee Values:

joe = Joe bob = Bob Values After Reference Assignment: joe = Joe bob = Joe Values After Changing One Instance: joe = Bobbi Jo bob = Bobbi Jo
Original Height Values: joe = 71 bob = 59 Values After Value Assignment: joe = 71 bob = 71 Values After Changing One Instance: joe = 65 bob = 71

The difference seems self-evident. In the first sample, changing one of the values affects both references, because they are both referencing the same underlying object. In the second sample, changing one of the objects affects only that object, because when value types are copied, each object receives it own private copy. When you say bob = joe; in the second sample, you;re not assigning a reference (the comment is misleading). What you're doing is creating a new instance of the Height struct, copying all the values from joe and storing the new object as bob.

Tim Long's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c# or ask your own question .

  • The Overflow Blog
  • How we’re making Stack Overflow more accessible
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • MPs assuming office on the day of the election
  • Every time I see her, she said you've not been doing me again
  • What counts as a pet?
  • Zsh: enable extended_glob inline in a filename generation glob
  • What does it mean to echo multiple strings into a UNIX pipe?
  • Am I allowed to link code licensed under GPL to proprietary libraries?
  • Why don't programming languages or IDEs support attaching descriptive metadata to variables?
  • Why is "a black belt in Judo" a metonym?
  • Why does Air Force Two lack a tail number?
  • Is there a reason SpaceX does not spiral weld Starship rocket bodies?
  • Will lights plugged into cigarette lighter drain the battery to the point that the truck won't start?
  • What is the interpretation of the word ' quickly' as used by Jesus in Jn 13:26-27?
  • Is there such a thing as a probability of God?
  • How can sound travel as a transverse wave?
  • Direct limits in homotopy category
  • Why do individuals with revoked master’s/PhD degrees due to plagiarism or misconduct not return to retake them?
  • section numbers in PDF outline
  • test & train for very very small data
  • Embedding rank of finite groups and quotients
  • Can an elf and a firbolg breed?
  • Tiling a rectangle with one-sided P-pentominoes
  • How to deal with a boss that is using non-related arguments in a dissent?
  • Why does electromagnetic and weak force get stronger at high energies and other way around for strong force?
  • Overlap two Chess Games

assignment by value or reference

IMAGES

  1. Value and reference assignment

    assignment by value or reference

  2. Passing by Value vs. by Reference Visual Explanation

    assignment by value or reference

  3. By Value and By Reference in PHP

    assignment by value or reference

  4. How to Write Reference in Assignment ️ Useful Guide

    assignment by value or reference

  5. Python : What is it? Pass by Value or Pass by Reference? It is Pass by

    assignment by value or reference

  6. Python Pass By Reference Or Value With Examples

    assignment by value or reference

COMMENTS

  1. JavaScript by reference vs. by value

    Javascript is always pass by value, but when a variable refers to an object (including arrays), the "value" is a reference to the object. Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object. However, changing a property of an object referenced by a variable ...

  2. Python : When is a variable passed by reference and when by value

    34. Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object.

  3. The Difference Between Values and References in JavaScript

    The first statement let a = 1 defines a variable a initialized with the number 1.. The second statement let b = a defines another variable b and initializes it with the value of a variable — which is passing by value. Simpler, a copy of the number 1 is assigned to b.. Later, b = b + 2 increases by 2 and becomes 3.b variable changes, and this change doesn't affect the value of a.

  4. All you need to know on by reference vs by value

    As you saw Ruby only uses pass by reference value while JavaScript uses a mixed strategy. Still, the behavior is the same for almost all the data types due to the different implementation of the data structures. Most of the mainstream languages are either copied and passed by value or copied and passed by reference value. For the last time ...

  5. Understanding Assign by Value and Assign by Reference in JavaScript

    Assign by Value: When assigning a primitive data type (like numbers, strings, or booleans), the value is copied to the new variable. Any changes made to one variable won't affect the other. For example: Assign by Reference: When assigning objects (including arrays and functions), the reference to the object is copied, not the actual value. So ...

  6. Object references and copying

    Object references and copying. One of the fundamental differences of objects versus primitives is that objects are stored and copied "by reference", whereas primitive values: strings, numbers, booleans, etc - are always copied "as a whole value". That's easy to understand if we look a bit under the hood of what happens when we copy ...

  7. Pass by Reference in Python: Background and Best Practices

    Python passes arguments neither by reference nor by value, but by assignment. Below, you'll quickly explore the details of passing by value and passing by reference before looking more closely at Python's approach. After that, you'll walk through some best practices for achieving the equivalent of passing by reference in Python. Remove ads.

  8. Explaining Value vs. Reference in Javascript

    Let's pretend that address is a new data type that is passed by value, just like number or string. An address points to the location, in memory, of a value that is passed by reference. Just like a string is denoted by quotation marks ('' or ""), an address will be denoted by arrow brackets, <>. When we assign and use a reference-type variable ...

  9. Quick Tip: How JavaScript References Work

    The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference. On variable assignment, the scalar primitive values (Number, String ...

  10. Copy by Value vs Reference

    In this short blog I will explain the differences between the two and provide examples along the way. Variables will either be passed a copy of the value of they're being assigned, or be passed a reference to the value they're being assigned. Copy by Value. When working with primitive data types (numbers, strings, Booleans, null, and undefined ...

  11. Python : What is it? Pass by Value or Pass by Reference? It is ...

    A function with pass-by-reference. Python's Pass by Assignment: Python's behavior is neither purely pass-by value nor pass-by-reference. Instead, it employs a mechanism called "pass by ...

  12. Learning how references work in JavaScript

    The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference; On variable assignment, the scalar primitive values (Number, String ...

  13. Does Java pass by reference or pass by value?

    Passing by value means we pass a copy of the value.; Passing by reference means we pass the real reference to the variable in memory.; Java object references are passed by value. All object ...

  14. Pass by reference vs value in Python

    In the article, we will be discussing the concept of how to pass a value by reference in Python and try to understand pass-by-reference examples in Python. Table of Content. ... Python utilizes a system, which is known as "Call by Object Reference" or "Call by assignment". If you pass arguments like whole numbers, strings, or tuples to a ...

  15. Reference and Value Semantics

    Value (or "copy") semantics mean assignment copies the value, not just the pointer. C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the ...

  16. C# assign by reference

    That's how it works already. Strings are a reference type- your variable A is a reference (like a pointer) to a string on the heap, and you are just copying the pointer's value (the address of the string) into the variable B. Your example doesn't change the value of A when you assign "abcd" to B because strings are treated specially in .net.

  17. Assignment operators

    In this article. The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or ...

  18. Is Python call by reference or call by value

    Python utilizes a system, which is known as "Call by Object Reference" or "Call by assignment". If you pass arguments like whole numbers, strings, or tuples to a function, the passing is like a call-by-value because you can not change the value of the immutable objects being passed to the function. Passing mutable objects can be considered as call by reference or Python pass by ...

  19. Assigning in Java?

    In Java, your variables can be split into two categories: Objects, and everything else (int, long, byte, etc). A primitive type (int, long, etc), holds whatever value you assign it. An object variable, by contrast, holds a reference to an object somewhere. So if you assign one object variable to another, you have copied the reference, both A ...

  20. Why Assignment Operator Overloading Must Return Reference?

    Prerequisite: Operator Overloading The assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types. Assignment operator overloading is binary operator overloading.Overloading assignment operator in C++ copies all values of one

  21. C# Reference type assignment VS value type assignment

    3. One is a structure and the other is a class. This seems like an overly complicated example involving more than just value and reference differences but the differences between classes and structs as well. When one struct is assigned to another a copy is made. When one class is assigned to another only the reference changes.