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 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);

In the active code below, we access the instance variables of Point object black using dot notation and output their values. Next, we output the distance from the origin.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 5 activities on this page