OO Encapsulation  «Prev  Next»
Lesson 8 Using a member function
Objective Add a member function to the ch_stack struct.

Using a Member Function in C++

Member functions are written just like any other functions.
One difference, though, is they can use the data member names as is. Thus, the member functions in ch_stack use top and s in an unqualified manner.
When invoked on a particular object of type ch_stack, the member functions act on a specified member of that object.
Member functions that are defined within the struct are implicitly inline. As a rule, only short, heavily used member functions should be defined with the struct. Other member functions should be defined external to the struct. We will look at defining external member functions in the next module.

Members of a Class

By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifier automatically has private access. For example:

class CRectangle {
 int x, y;
 public:
  void set_values (int,int);
   int area (void);
 } rect;

Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class contains four members:
  1. two data members of type int (member x, member y) with private access (because private is the default access level) and
  2. two member functions with public access: set_values() and area(),
  3. of which for now we have only included their declaration, not their definition.


Notice the difference between the class name and the object name: In the previous example, CRectangle was the class name (i.e., the type), whereas rect was an object of type CRectangle. It is the same relationship int and a have in the following declaration:
int a;
where int is the type name (the class) and a is the variable name (the object).
After the previous declarations of CRectangle and rect, we can refer within the body of the program to any of the public members of the object rect as if they were normal functions or normal variables, just by putting the object's name followed by a dot (.) and then the name of the member. All very similar to what we did with plain data structures before. For example:
rect.set_values (3,4);
myarea = rect.area();

C++ Member Function - Exercise

At the level of programming, a class is a data structure with
  1. data members for representing the various properties of the different object instances of the class, and
  2. with member functions for representing the behavior of the class.

Click the Exercise link to add a member function to the ch_stack struct.
C++ Member Function - Exercise