Oops!関数をoverrideしようとしたらミスってた!
#include <iostream> class Base { public: virtual void say_hello() const{ std::cout << "this is Base class object" << std::endl; } virtual ~Base() {}; }; class Derived: public Base { public: virtual void say_hello() { std::cout << "this is Derived class object" << std::endl; } virtual ~Derived() {}; }; int main(){ Base *ptrb = new Base(); Base *ptrd = new Derived(); ptrb->say_hello(); ptrd->say_hello(); delete ptrb; delete ptrd; return 0; }
this is Base class object this is Base class object
ptrd->say_hello();
は、this is Derived class object
となってほしい。
const
が抜けちゃっているせいで、関数がredefineされてしまっています。
こうならないようにも、ちゃんとC++には明示的にoverrideすんで!と指定することができます。
#include <iostream> class Base { public: virtual void say_hello() const{ std::cout << "this is Base class object" << std::endl; } virtual ~Base() {}; }; class Derived: public Base { public: virtual void say_hello() const override{ std::cout << "this is Derived class object" << std::endl; } virtual ~Derived() {}; }; int main(){ Base *ptrb = new Base(); Base *ptrd = new Derived(); ptrb->say_hello(); ptrd->say_hello(); delete ptrb; delete ptrd; return 0; }
こうするだけ!簡単。
気をつけないといけないのは、overrideを指定しても、全く同じ関数でない場合はredefineしてしまうので注意。
(まあoverrideと指定してconstを忘れたりすると、何をoverrideしたらいいの?
とコンパイルエラーになり、一目瞭然になるので、ちゃんとつけたほうがいいよってお話。
final
finalというのも反対にあります。
これ以上オーバーライドさせたくないときは、final
を使います。
この場合は、クラス単位および関数単位で使用する。
class Base { public: virtual void say_hello() const final{ std::cout << "this is Base class object" << std::endl; } virtual ~Base() {}; }; class Derived: public Base { public: virtual void say_hello() const override{ std::cout << "this is Derived class object" << std::endl; } virtual ~Derived() {}; };
とすれば、もちろんコンパイルエラーになります。
error: declaration of 'say_hello' overrides a 'final' function