Skip to main content

Section 15.3 Operations on structures

Most of the standard operators, like mathematical operators ( +, %, -, etc...), comparison operators (==, >, etc...), and stream operators (<<, >>), do not work on structures. It is possible to define those operators (covered in ChapterΒ 20), but the operators will not work until we do so.
One operator that does work β€œout of the box” for structures is the assignment operator. It can be used in two ways: to initialize the instance variables of a structure from a list of values or to copy the instance variables from one structure to another. An initialization looks like this:
Point blank = { 3.0, 4.0 };
The values in curly braces get assigned to the instance variables of the structure one by one, in order. So in this case, x gets the first value and y gets the second.
This syntax can also be used in an assignment statement. So the following is legal.
Point blank;
blank = { 3.0, 4.0 };
The values are always used in order, so if we have a Person struct that looks like:
struct Person {
  string name;
  int age;
};
We could initialize a Person like this:
Person p = { "Alice", 30 };
But trying to use:
Person p = { 30, "Alice" };
Would be an error, because the types do not match the order of the instance variables (string then int).
The second use of assignment is to copy one struct into another:
Point p1 = { 3.0, 4.0 };
Point p2 = p1;
It is important to note that an assignment makes a copy of a struct. Once the assignment has been made, changing one struct has no effect on the other. This Codelens demonstrates by coping a struct and then changing one of the copies.
Listing 15.3.1.

Checkpoint 15.3.1.

Construct a block of code that correctly initializes the instance variables of a structure.

Checkpoint 15.3.2.

Which operators do NOT work on structures. Select all that apply.
  • %
  • The modulo operator does not work on structures.
  • =
  • The assignment operator does work on structures.
  • >
  • The greater than operator does not work on structures.
  • ==
  • The equality operator does not work on structures.
  • +
  • The addition operator does not work on structures.
You have attempted of activities on this page.