Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 8.3 Accessing instance variables
You can read the values of an instance variable using the same syntax we used to write them:
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 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 8.3.1. In this active code, we access the instance variables of Point
object black
using dot notation and output their values. Next, we output the distance from the origin.
Checkpoint 8.3.1 .
In
string x = thing.cube;
, what is the object and what is the instance variable we are reading the value of?
string
is the instance variable,
cube
is the object
string
is a data type.
x
is the instance variable,
thing
is the object
x
is the local variable.
thing
is the instance variable,
cube
is the object
Consider the placement of thing
– it is before the .
cube
is the instance variable,
thing
is the object
Yes, we access the instance variable cube
of the object thing
using the dot operator.
cube
is the instance variable,
string
is the object
string
is a data type.
Checkpoint 8.3.2 .
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;
}
Spaces need to be printed out like any other output.
There are no spaces in the correct output.
The order in which the variables are printed out do not need to match the order in which they are declared.
The order in which the variables are printed out do not need to match the order in which they are declared.
Checkpoint 8.3.3 .
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?
No parentheses are needed.
You should be assigning to the local variable x
.
You should be assigning to the local variable x
.
This is the correct way to assign the value of y
to x
.
You have attempted
of
activities on this page.