Sams Teach Yourself C++ in 21 Days

(singke) #1
Answers 869

D


9: char* GetString() { return itsString; }
10: private:
11: char* itsString;
12: };
13:
14: OutOfMemory::OutOfMemory(char * theType)
15: {
16: itsString = new char[80];
17: char warning[] = “Out Of Memory! Can’t allocate room for: “;
18: strncpy(itsString,warning,60);
19: strncat(itsString,theType,19);
20: }
21:
22: int main()
23: {
24: try
25: {
26: int *myInt = new int;
27: if (myInt == 0)
28: throw OutOfMemory(“int”);
29: }
30: catch (OutOfMemory& theException)
31: {
32: cout << theException.GetString();
33: }
34: return 0;
35: }


  1. The following is one possible answer:
    0: // Exercise 20.3
    1: #include
    2: using namespace std;
    3: // Abstract exception data type
    4: class Exception
    5: {
    6: public:
    7: Exception(){}
    8: virtual ~Exception(){}
    9: virtual void PrintError() = 0;
    10: };
    11:
    12: // Derived class to handle memory problems.
    13: // Note no allocation of memory in this class!
    14: class OutOfMemory : public Exception
    15: {
    16: public:
    17: OutOfMemory(){}
    18: ~OutOfMemory(){}
    19: virtual void PrintError();
    20: private:
    21: };


32 0672327112_app_d.qxd 11/19/04 12:30 PM Page 869

Free download pdf