Tag Archives: object vs reference semantics

Value semantics vs reference semantics

Value Semantics:

Behavior where variables are copied
when assigned to each other or passed as parameters.

  • Primitive types in C++ use value semantics.
  •  Modifying the value of one variable does not affect other   Example:
    int x = 15;
    int y = x; // x = 15, y = 15
    y = 17; // x = 15, y = 17
    x = 18; // x = 18, y = 17

Reference Semantics: Behavior where variables refer to a
common value when assigned to each other or passed as
parameters.

  • Object types in C++ use reference semantics.
  •  Object variables do not store an object; they store the address of
    an object’s location in the computer memory and graphically
    addresses are represented as arrows.

Example:
Point p = new Point(30 ,28);

If two object variables are assigned the same object, the
object is NOT copied; instead, the object’s address is
copied.

  • As a result, both variables will point to the same object.
  • Calling a method on either variable will modify the same object.

Example:
Point x = new Point(13,12);
Point y = x;

TwoPointers

Why Reference Semantics ?

Objects have reference semantics for following reasons:

  • efficiency: Objects can be large and bulky. Having to copy them
    every time they are passed as parameters would slow down the
    program.
  • sharing: Since objects hold important state, it is often more
    desirable for them to be shared by parts of the program when
    they’re passed as parameters. Often we want the changes to
    occur to the same object.