Search code examples
c++exceptioncompiler-errorsprivatemingw32

Why is this compiler error happening?


I am working on exception handling for a piece of software I write in C++. I encounter a compiler error (using g++ (GCC) 4.8.1 / mingw32) I don't understand, here is a minimal example:

#include <iostream>
#include <exception>

class Bad_Img_Load: public std::exception {
    //public:
    virtual const char* what() const throw(){
        return "An image could not be loaded.";
    }
};

int main () {
    try{
        throw Bad_Img_Load();
    }catch (Bad_Img_Load& e){
        std::cout << e.what() << '\n';
    }
    return 0;
}

The error is:

a.cpp: In function 'int main()':
a.cpp:6:22: error: 'virtual const char* Bad_Img_Load::what() const' is private
  virtual const char* what() const throw(){
                      ^
a.cpp:15:25: error: within this context
     std::cout << e.what() << '\n';
                         ^

Note that if I uncomment the line 'public:' then it works just fine. But the class 'exception' from which it inherits defines everything as public. So I don't understand why this error crops up at all.


Solution

  • It doesn't matter if whether the class you're inheriting from has all it's members public. If you overload an inherited class' public function with a (in your code implicitly specified) private access-specifier, then the overload is private. Technically, you could say that you're overloading the access-specifier too.