Sams Teach Yourself C++ in 21 Days

(singke) #1
Handling Errors and Exceptions 739

20


It is tedious and error-prone to have each of these catchstatements individually print the
appropriate message. This job belongs to the object, which knows what type of object it
is and what value it received. Listing 20.8 takes a more object-oriented approach to this
problem, using virtual functions so that each exception “does the right thing.”

LISTING20.8 Passing by Reference and Using Virtual Functions in Exceptions


0: #include <iostream>
1: using namespace std;
2:
3: const int DefaultSize = 10;
4:
5: class Array
6: {
7: public:
8: // constructors
9: Array(int itsSize = DefaultSize);
10: Array(const Array &rhs);
11: ~Array() { delete [] pType;}
12:
13: // operators
14: Array& operator=(const Array&);
15: int& operator[](int offSet);
16: const int& operator[](int offSet) const;
17:
18: // accessors
19: int GetitsSize() const { return itsSize; }
20:
21: // friend function
22: friend ostream& operator<<
23: (ostream&, const Array&);
24:
25: // define the exception classes
26: class xBoundary {};
27: class xSize
28: {
29: public:
30: xSize(int size):itsSize(size) {}
31: ~xSize(){}
32: virtual int GetSize() { return itsSize; }
33: virtual void PrintError()
34: {
35: cout << “Size error. Received: “;
36: cout << itsSize << endl;
37: }
38: protected:
39: int itsSize;
40: };
41:
Free download pdf