OOPortal
J2EEOnline RationalDB
prev next prev next
Course navigation
Lesson 11 Class or struct?
Objective Design a Person Class
The Person class contains members to store data and a member function to print out the data members.
Classes in C++ are introduced by the keyword class.
They are a form of struct whose default privacy specification is private.
Thus struct and class can be used interchangeably with the appropriate access specifications.
Let us look at how we would turn our struct ch_stack into a class. First, here is the struct:
const int max_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);
   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); }
const int  max_len = 40;
class 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);
  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); 
 }
The only difference is the keyword class, which is used in place of struct.
Person Class Exercise
Click the Exercise link below to design a class called person that contains members to store data and a member function to print out the data members.
Person Class Exercise
Course navigation