8.3. Accessing instance variables

You can read the values of an instance variable using the same syntax we used to write them:

int x = blank.x;

The expression blank.x means “go to the object named blank and get the value of x.” In this case we assign that value to a local variable named x. Notice that there is no conflict between the local variable named x and the instance variable named x. The purpose of the member access operator is to identify which variable you are referring to unambiguously.

You can use the member access operator as part of any C++ expression, so the following are legal.

cout << blank.x << ", " << blank.y << '\n';
double distance = sqrt(blank.x * blank.x + blank.y * blank.y);

In the active code below, we access the instance variables of point object blank and output their values. Next, we display the distance from the origin.

Example accessing_instance_variables_AC_1
 1#include <cmath>
 2#include <iostream>
 3
 4struct point {
 5    double x;
 6    double y;
 7};
 8
 9int main() {
10   point blank;
11   blank.x = 3.0;
12   blank.y = 4.0;
13   std::cout << blank.x << ", " << blank.y << '\n';
14   double distance = std::sqrt(blank.x * blank.x + blank.y * blank.y);
15   std::cout << distance << '\n';
16}

Q1

In string x = thing.cube;, what is the object and what is the instance variable we are reading the value of?

Q2

What will print?

struct blue {
  double x, y;
};

int main() {
  blue blank;
  blank.x = 7.0;
  blank.y = 2.0;
  cout << blank.y << blank.x;
  double distance = blank.x * blank.x + blank.y * blank.y;
  cout << distance << '\n';
}

Q3

You want to go to the object named circle and get the integer value of y, then assign it to the local variable x. How would you do that?