C++キーワードのoverride

2251 ワード

非オリジナル、stackoverflowから転載
確かにoverrideはkeywordではありません
The override keyword serves two purposes:
  • It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."(人に見せる)
  • The compiler also knows that it's an override, so it can "check"that you are not altering/adding new methods that you think are overrides.(コンパイラに確認させる)
  • To explain the latter:
    class base
    {
      public:
        virtual int foo(float x) = 0; 
    };
    
    
    class derived: public base
    {
       public:
         int foo(float x) override { ... do stuff with x and such ... }
    }
    
    class derived2: public base
    {
       public:
         int foo(int x) override { ... } 
    };

    In derived2 the compiler will issue an error for "changing the type". Without override , at most the compiler would give a warning for "you are hiding virtual method by same name".