Accessing an Object’s Members

Accessing an Object’s Members
Accessing an Object’s Members
Public members of a class object are accessed with the dot operator. For example, the following statements call the setRadius function of circle1 and circle2.
circle1.setRadius(1); // This sets circle1's radius to 1
circle2.setRadius(2.5); // This sets circle2's radius to 2.5
Now that the radii have been set, we can call the getArea member function to return the area of the Circle objects:
cout << "The area of circle1 is " << circle1.getArea() << endl;
cout << "The area of circle2 is " << circle2.getArea() << endl;
This Program  is a complete program that demonstrates the Circle class. Notice that the statements to create and use Circle objects are in main, not in the class declaration.


PROGRAM

1  // This program demonstrates a simple class.
2  #include <iostream>
3  #include <cmath>
4  using namespace std;
5
6  // Circle class declaration
7  class Circle
8  { private:
9  double radius;
10
11  public:
12  void setRadius(double r)
13  { radius = r; }
14
15  double getArea()
16  { return 3.14 * pow(radius, 2); }
17  };
18
19  int main()
20  {
21  // Define 2 Circle objects
22  Circle circle1,
23 circle2;
24
25 // Call the setRadius function for each circle
26 circle1.setRadius(1); // This sets circle1's radius to 1
27 circle2.setRadius(2.5); // This sets circle2's radius to 2.5
28
29 // Call the getArea function for each circle and
30 // display the returned result
31 cout << "The area of circle1 is " << circle1.getArea() << endl;
32 cout << "The area of circle2 is " << circle2.getArea() << endl;
33
34 return 0;
35 }

Program Output

The area of circle1 is 3.14
The area of circle2 is 19.625

Notice in lines 13 and 16 of Program  how the class member functions setRadius and getArea use the member variable radius. They do not need to use the dot operator to reference it because member functions of a class can access member variables of the same class like regular variables, without any extra notation. Notice also that the class member function getArea only uses, but does not modify, the member variable radius. A function like this, that uses the value of a class variable but does not change it, is known as an accessor. The function setRadius, on the other hand, modifies the contents of radius. A member function like this, which stores a value in a member variable or changes its value, is known as a mutator. Some programmers refer to mutators as set functions or setter functions because they set the value of a class variable, and refer to accessors as get functions or getter functions because they just retrieve or use the value.

Previous
Next Post »