Skip to main content

Section 15.2 Accessing instance variables

You can read the values of an instance variable using the same syntax we used to initialize them:
int x = blank.x;
The expression blank.x means “go to the memory named blank and get the value stored in the part named 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 dot notation is to identify which variable you are referring to unambiguously.
You can use dot notation as part of any C++ expression, so the following are legal.
cout << blank.x << ", " << blank.y << endl;
double distance = sqrt(blank.x * blank.x + blank.y * blank.y);
Listing 15.2.1. In this Codelens, we access the instance variables of Point struct blank using dot notation and output their values. Next, we output the distance from the origin.

Checkpoint 15.2.1.

In string x = bar.cube;, what is the struct and what is the instance variable we are reading the value of?
  • x is the instance variable, bar is the struct
  • x is the local variable.
  • bar is the instance variable, cube is the struct
  • Consider the placement of bar. It is before the .
  • cube is the instance variable, bar is the struct
  • Yes, we access the instance variable cube of the struct bar using the dot operator.
  • cube is the instance variable, foo is the struct
  • foo is a data type in this sample.

Checkpoint 15.2.2.

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 << endl;
}
  • 2 7 53
  • Spaces need to be printed out like any other output.
  • 7 2 53
  • Spaces need to be printed out like any other output.
  • 2753
  • There are no spaces in the correct output.
  • 7253
  • The order in which the variables are printed out do not need to match the order in which they are declared.

Checkpoint 15.2.3.

You want to go to the struct named c1 and get the integer value of y, then assign it to the local variable x. How would you do that?
  • int y = c1.x();
  • No parentheses are needed.
  • int c1 = x.y;
  • You should be assigning to the local variable x.
  • int y = c1.x;
  • You should be assigning to the local variable x.
  • int x = c1.y;
  • This is the correct way to assign the value of y to x.
You have attempted of activities on this page.