OO Encapsulation  «Prev  Next»
Lesson 7Member functions
Objective Understand how to declare a member function.

Member Functions in C++

The member function declaration is included in the struct declaration and is invoked by using access methods for structure members.
The idea is that the functionality required by the struct data type should be directly included in the struct declaration.
This improves the encapsulation of the ADT by packaging its operations directly with its data representation. Here is an example of a stack ADT that declares the various functions associated with the stack as member functions:

const intmax_len = 40;

struct ch_stack {
  //data representation
   char s[max_len]; 
   int  top;
   enum{ EMPTY = -1, FULL = max_len - 1 };

  //operations represented as member functions
   void  reset() { top = EMPTY; }
   void  push(char c) {
     assert(top != FULL);
     s[top] = c;
   char  pop() {
     assert(top!= EMPTY);
     return s[top--];
   char  top_of() {
     assert(top!= EMPTY);
     return s[top];
   bool  empty()
     {return (top == EMPTY); }
   bool  full()
     {return (top == FULL); }