OO Encapsulation  «Prev  Next»
Lesson 9 Private and public access
Objective Limiting access of members using private keyword.

Private and Public Access in C++

The concept of struct is augmented in C++ to allow functions to have public and private members. Inside a struct, the use of the keyword private followed by a colon restricts the access of any members that come after the keyword. Let us modify our example of ch_stack to hide its data representation and explore how private works. We will make the member functions public and the data members private:

const int max_len = 40;
struct ch_stack {
  public:
  void reset() { top = EMPTY; }
  void push(char c)
  {
      assert(top != FULL);
      top++;
      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); }
  private: 
    char  s[max_len]; 
    int top;
    enum { EMPTY = -1, FULL = max_len - 1 };
};