SafeInt



next up previous
Next: SafeFloat Up: TECHNIQUES AND EXAMPLES Previous: TECHNIQUES AND EXAMPLES

SafeInt

 

The following simple code illustrates many of C++'s features for controlling access to data. Following the class definition, the general use of some C++ features in safety critical code and some comments specific to class SafeInt are discussed. Note that in practice this class would occupy two files: SafeInt.h would include the declaration of the class, its attributes and functions, while SafeInt.c++ would include the definitions (bodies) of the functions. The two are combined below for exposition purposes.

[ 1]   class SafeInt
[ 2]   {
[ 3]   private:
[ 4]       long int i;    // the actual value of the safe integer
[ 5]       operator int() const { return i;} 
[ 6]    
[ 7]   public:
[ 8]       SafeInt(const SafeInt other) { i = other.i;}
[ 9]       SafeInt() { i = 0;}
[10]       SafeInt(const int value) { i = value;}
[11]       ~SafeInt() {}
[12]   
[13]       SafeInt operator=  (const SafeInt value)   { i = value.i; return(*this);}
[14]       SafeInt operator=  (const int     value)   { i = value;   return(*this);}
[15]       SafeInt operator+  (const int     b) const { return(SafeInt(i+b));}
[16]       SafeInt operator+  (const SafeInt b) const { return(SafeInt(i+b.i));}
[17]       SafeInt operator/  (const SafeInt b) const { if (b.i == 0) ... else ...}
[18]       SafeInt operator%  (const SafeInt b) const { ... }
[19]       int     operator!= (const SafeInt b) const { return(i != b.i);}
[20]       SafeInt operator++ ()      { i++; return(*this);}
[21]       SafeInt operator++ (int _) { SafeInt t = *this; i++; return(t);}
[22]       int     value()    {return i;}
[23]   };

Notes



next up previous
Next: SafeFloat Up: TECHNIQUES AND EXAMPLES Previous: TECHNIQUES AND EXAMPLES



David Binkley
Thu Feb 29 10:02:46 EST 1996