Skip to main content

Section 17.7 Using the Contained Members

Now let’s add and use some getters to the Circle class:
Listing 17.7.1.
The getRadius is straightforward. It just returns the m_radius that the Circle stores. But getX() is more complicated. The Circle does not have an x or a m_x that it can return. What it does have is a Point m_center. It needs to rely on that Point to access the x location.
Any time there is something related to the center, or working with Point logic, the Circle will hand that work off to the Point. Here that means that on line 34, when we ask the Circle for its x value, it in turn asks the Point m_center for its x value (line 19) and returns that answer to us.

Insight 17.7.1.

private is enforced at the class level. Even though a Circle β€œowns” a Point, it can’t directly access the Point’s private data. It would be an error to write m_center.m_x on line 19 in an attempt to directly access the member variable of the Point.
Let’s add another function that uses existing Point logic to help Circle do a job. We want to add a method that tells us if a Point is inside a Circle. We can do that by comparing the radius of the Circle and the distance from the Point to the center of the Circle. If that distance is less than the radius, then the Point is inside the Circle.
Listing 17.7.2.
Finding the distance between two points is a job for a Point, not the Circle. So when we ask c1.contains(Point(3.2, 2.0)), the circle starts by asking its center Point to calculate the distance to that point (m_center.distanceTo(p)). It then uses that value to compute the final answer.

Checkpoint 17.7.1.

Checkpoint 17.7.2.

Imagine a Circle member function intersects(const Circle& other). What variables can be directly accessed inside the function.
  • m_radius of the current object
  • m_center of the current object
  • other.m_radius
  • other.m_center
  • m_center.m_x
  • No, m_x is private to the Point class. You can only access it indirectly through a public function of the Point class.
  • other.m_center.m_x
  • No, m_x is private to the Point class. You can only access it indirectly through a public function of the Point class.
You have attempted of activities on this page.