0

I am trying to change the message for bad_alloc.

#include <iostream>
#include <iomanip>
#include <stdexcept>

using std::logic_error;
using std::bad_alloc;


class OutOfRange : public logic_error {
   public:
      OutOfRange(): logic_error("Bad pointer") {}
};


class OutOfMem : public bad_alloc {
   public:
      OutOfMem(): bad_alloc("not enough memory") {}
};

OutOfRange() works fine, but OutOfMem sends me an error:

No matching function for call to std::bad_alloc::bad_alloc(const char[21])

Hannele
  • 9,301
  • 6
  • 48
  • 68
KarlaE
  • 27
  • 5

1 Answers1

2

The compile error is telling you that that bad_alloc constructor does not take a char *. e.g. See here
Instead, note that exception what method is vritual and use that instead.

   class OutOfMem : public bad_alloc {
      public:
         OutOfMem() {}
         const char *what() const {
             return "not enough memory";
         }
   };

Edit: note you might have to state it doesn't throw as follows:

 //... as before
 virtual const char * what() const throw () {
     return "not enough memory";
 }
 // as before ...
doctorlove
  • 18,872
  • 2
  • 46
  • 62
  • I try that, it send me an error looser throw specifier for `virtual const char* OutOfMem::what() const' – KarlaE Nov 19 '13 at 17:29
  • How is `what` defined in std::exception in your setup? Does it have a throw specifier? – doctorlove Nov 19 '13 at 17:39
  • well i only have this on my header #include #include #include using std::logic_error; using std::bad_alloc; – KarlaE Nov 19 '13 at 17:45
  • The solution will depend on what version (of gcc I presume) you are using see here: http://stackoverflow.com/questions/4282578/exception-specifications-when-deriving-from-stdexception-in-c11 – doctorlove Nov 19 '13 at 17:48
  • Or indeed http://stackoverflow.com/questions/9635464/what-the-c-standard-says-about-loosing-throw-specifier-in-default-destructor – doctorlove Nov 19 '13 at 17:49