Freigeben über


The override keyword can be used in C++ afterall (redux on refactoring virtual functions)

Yesterday I wrote about the two methods I use to refactor a virtual function and make sure that I find all of the derived implementations.  In the entry I lamented that I would like to have the C# keyword override implemented in C++.  Well, apparently it is (at least in the Microsoft compiler)!  Check it out for yourself on MSDN.  Now since it was not a part of the language from the start, you cannot assume that when you change the super class's virtual function signature that the derived classes will not compile, but if you use the override keyboard keyword during development when you initially implement the derived classes, it will flag the mistake where you are creating a new virtual function instead of overriding an existing one. 

 So, let's take yesterday's classes and use the override keyword

     class Base { public: virtual void Foo() {}; };

    class Derived : public Base { public: virtual void Foo() override {}; };

Now when we change void Base::Foo() to void Foo(Bar* PBar), we get the following compiler error

     main.cpp(6) : error C3668: 'Derived::Foo' : method with override specifier 'override' did not override any base class methods

This is much better then the previous situation, although it is not as good as in the C# environment. If you forget to add the override keyword, you can still encounter the mistake of creating a new virtual function instead, but this is better then nothing!

 

Comments

  • Anonymous
    October 29, 2006
    But most importantly, it supports "sealed"! With which you mark methods that will never be overriden or classes that will never be extended, which "freezes" the vtable turning internal virtual calls into straight calls

  • Anonymous
    October 30, 2006
    Very cool.  Here is the MSDN link, http://msdn2.microsoft.com/en-us/library/0w2w91tf.aspx.  Looking over the feature list, it looks like nearly all of the C# constructs can now be used in native C++...definitely a feature that has not been made very visible to the outside community (or even withing Microsoft ;)).

  • Anonymous
    August 15, 2007
    You have spent too much time developing keyboard drivers:'the override keyboard during development', should have been the override keyword during development.

  • Anonymous
    August 17, 2007
    That is not a symptom of working on input for too long, it is a symptom of not running a spell check and overall poor typing skills ;) d