15.6 END OF CHAPTER PROGRAMS

15.6.1 Array with bounds checking I

Arrays in C++ do not check for bounds. It creates many bugs. It will be a nice idea if program aborts, when array is accessed out of bounds. An array can be of any type. If we do not want to write separate routines for every type, a template class is the only solution.

Problem: Write a program to create class to implement a “Safe Array”. It should be using template <class T>.

Solution: For simplicity, let us fix size of an array as 100. Let us define a class Sarray. Rules for this class are as follows.

  1. size = 100
  2. index from 0 to size -1
  3. If array sought outside bound program aborts.
  4. Function safeput() used to assign value to array element.
  5. Function safeget() used to return the array ...

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.