3

I'm following a book that teaches C++ according to the standard C++11. The book shows an example that marks a subclass as explicit.

From what I've gathered, this will make the compiler check for errors that have to do with dynamic binding, and you must also explicitly use the override keyword whenever you override a virtual function otherwise it won't work. I did set up a small program to test this but I got an error. And I've never seen examples of the keyword explicit be used like that anywhere else anyway.

Has the book provided inaccurate information or have I just missed something? Should I just use the override keyword on it's own instead?

class base {
public:
    virtual void f() {
        cout << "Called from base" << endl;
    }
};

class derived explicit : public base {
public:
    void f() override {
        cout << "Called from derived" << endl;
    }
};

Writing c++ -std=c++11 main.cpp -o main.exe in the terminal gave me the following error:

error: expected unqualified-id 
class derived explicit : public base {
                   ^
Quentin
  • 62,093
  • 7
  • 131
  • 191
sam
  • 99
  • 5

1 Answers1

6

Using explicit this way is not valid C++, in any standard. From cppreference on explicit:

1) Specifies that a constructor or conversion function (since C++11) is explicit, that is, it cannot be used for implicit conversions and copy-initialization.
2) [...] (C++20 specific...)

... and most importantly:

The explicit specifier may only appear within the decl-specifier-seq of the declaration of a constructor or conversion function (since C++11) within its class definition.

This does not cover the case you have shown from the book. Have a look at the curated list of books and consider switching to one of those.

lubgr
  • 37,368
  • 3
  • 66
  • 117