/* protected should be used to prevent a clumsy programmer from harming things. If the programmer is allowed to access the array "data", he could write A.data[36127] = 44, and who knows what would be ruined. Also, if the programmer is allowed to access size, she could write A.size = 36128; A.data[36127] = 44, and cause the same trouble. Sometimes it is not obvious that a simple variable should be protected,and thought is required. */ #include struct safearray { protected: int data[100]; int size; public: int getsize() { return size; } void setsize(int s) { if (s<0 || s>100) { cerr << "error in get\n"; exit(1); } size = s; } int get(int pos) { if (pos<0 || pos>=size) { cerr << "error in get\n"; exit(1); } return data[pos]; } void put(int pos, int val) { if (pos<0 || pos>=size) { cerr << "error in put\n"; exit(1); } data[pos] = val; } }; void main() { safearray A, B; A.setsize(20); B.setsize(90); cout << "A\n"; for (int i=0; i < A.getsize(); i+=1) A.put(i, i * 10001); cout << "B\n"; for (int i=0; i < 123; i+=1) B.put(i, i*2); }