-1

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.

Kenji
  • 335
  • 1
  • 15
  • Why do you expect the overridden function to be public if you declare it private? – Emil Laine Aug 30 '15 at 21:19
  • 1
    @Kenji: No they don't do it. I don't see it at the link. At your link they always catch the exception as `std::exception &e`, which is why they have access to *public* `e.what()`. They never catch their exceptions as user-defined type. You catch your exceptions as `Bad_Img_Load& e`, which is a completely different story. – AnT stands with Russia Aug 30 '15 at 21:23
  • You're right, AnT, I just noticed. Now I get it. I have no clue why that confused me so much. – Kenji Aug 30 '15 at 21:25

2 Answers2

1

There's basically one thing that makes struct and class different, and that's the default visibility. For struct the default is public and for class the default is private.

Whoever told you that class have default public visibility is wrong. Any beginners textbook will tell you the same.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Yes, you're right, I made a mistake. I wanted to write it should inherit the public from its superclass. – Kenji Aug 30 '15 at 21:16
1

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.

LostMikely
  • 130
  • 10