Search

B.6 — New virtual function controls: override, final, default, and delete

override

When working with derived classes, it’s fairly easy to inadvertently create a new virtual function in the derived class when you actually meant to override a function in the base class. This happens when you fail to properly match the function prototype in the derived class with the one in the base class. For example:

When this happens, it can be easy to make a function call to A() or B() and expect to get the derived version but end up getting the base version instead.

This phenomena can also easily occur when you add a new parameter to a function in Base but forget to update the version in Derived. When that happens, the function that was an override in Derived is no longer an override, and your code mysteriously stops working. These kinds of problems can be hard to find because the change that triggers them is so innocuous looking.

C++11 introduces a new identifier called override that allows you to explicitly mark functions you intend to be overrides. If the function is not an override, the compiler will complain about it. For example:

Although use of the override identifier is not required, it is highly recommended, as it will help prevent inadvertent errors.

(If you’re wondering why this was implemented as an identifier rather than a keyword, I presume this was done so that the name “override” can be used as a normal variable name in other contexts. If it had been defined as a keyword, it would be reserved in all contexts, which might break existing applications)

final

There are occasionally times when you don’t want to allow someone to override a virtual function, or even create a derived class. C++11 adds the identifier final to provide this functionality.

The following example shows the use of the final identifier to make a function non-overrideable:

The final identifier can also be used on classes to make them non-inheritable:

There are some legitimate reasons to make functions or classes final. For example, the most common use of final is to ensure that an immutable class stays immutable. An immutable class is a specially-designed class whose state cannot be modified after it is created. Without the final identifier, a derived class could add functions that could cause the class to become mutable. If the base class is made final, it cannot be subclassed, and this is avoided.

However, generally speaking, unless you have a really good reason, use of final should generally be avoided. And if you do use the final keyword, document why, as it will likely not be obvious to whoever inherits your code.

default

By default, C++ will provide a default constructor, copy constructor, copy assignment operator (operator=) and a destructor. If you provide alternate versions of any of these functions for your class, C++ will not provide a default version. However, in C++11, you can now specify that you would like the compiler to provide a default one anyway. This is done by prototyping the function and using the default specifier:

The default specifier can only be used with functions that have a default.

delete

More useful than the default specifier is the delete specifier, which can be used to disallow a function from being defined or called. One of the best uses of the delete specifier is to make a class uncopyable:

The delete specifier can also be used to make sure member functions with particular parameters aren’t called. For example:

In the above example, if you try to call Foo with a char, short, int, or long, those will all get implicitly converted to a long, which will then match Foo(long). Since Foo(long) has been deleted, the compiler will error.

If you want your class to only be called with very specific data types, you can turn off implicit conversions altogether by using a templated function to match everything that isn’t defined explicitly:

Index
B.5 -- Delegating constructors

59 comments to B.6 — New virtual function controls: override, final, default, and delete

  • ratsby

    Is this site dead? The tutorials on here are really good.

  • I was wondering the same thing

  • Raman009

    I have learnt a lot from this site. I registered just to say thanks to the developer.

    Thanks Adam.
    It was really a very nice learning experience.

  • ancode

    this site is really outstanding.
    I appreciate the person who developed the site.
    i have learned C++ just in 1 week by these tutorials.

  • Isn’t the correct way to call this

    class Foo
    {
    void Foo(long, long); // Can create Foo() with a long long
    void Foo(long) = delete; // But can’t create it with anything smaller
    };

  • Radu

    Registered to say thanks. This helped…a lot.

    So…thanks!

  • Anvi

    Im soo thankful to you.. its soo much fun to learn this way , amazing stuff..
    Thank u sooo much

  • Hashir

    Thanks a lot for these tutorials. I’ve learned a lot from your website. Definitely gonna use this website for future reference.

  • vladtodd

    this is the most recent post, and it is 2 years old. that probably means that the blog is dead, which makes me sad as i am really loving the tutorials. 🙁

  • waowao fantastic learn source file!

  • foxzhl

    The c++11 part is really helpful for its examples. Hope to see more about c++11!
    Thanks for helping me to re-confirm the c++11 knowledge.

  • DOBRESCU Mihai

    Hi, Alex.

    Thank you for a fine tutorial on the C++ programming language.

    It is always challenging to discover the intricacies of the computer science.

    Best Regards,
    Mihai Dobrescu

  • denier

    Thanks for this great tutorial!!
    I tried books but it was to boring.. learning from your tuts is very fast, you describe the subject and use examples immediately so it's really easy to follow.
    I started learning 12 days ago and now I know a lot from c++ thanks to you. Just enough to impress the professor with the upcoming c++ project using Qt4 and boost::asio::ip::tcp 🙂

  • puppi

    hi alex,
    thank you for tutorials. it’s amazing!
    i have just completed all tutorials, and i wonder what can i do know 🙂 is there any other tutorials about deep programming which may be you should recommend to us (all of us, your studens) ?

    thank you again.

  • Samir

    Bright tutorial. Thank you much Alex.

  • Turgut

    I really profited a lot from these tutorials. It is one of the best I have come accross so far. Everything I looked for, I found it here. Thank you very much for this great work, and I hope you keep going.
    Best regards…

  • mona

    the best site to learn cpp…thanx a lot

  • Mickey

    Thanks for the tutorials.

  • Wayne

    This is truly a great C++ tutorial. It’s better than most of the textbooks out there. Bravos to the author!

  • Fabrice Dai

    Thank you very much for teaching me so much about c++!
    ^_^

  • Matt

    Found some typos:
    * "subclasses" should be "subclassed": "If the base class is made final, it cannot be subclasses, and this is avoided."
    * "whomever" should be "whoever": "…as it will likely not be obvious to whomever inherits your code."

  • Reaversword

    Would be possible to use "delete" to avoid that a derived class inherits a base function?

    • Alex

      It doesn’t appear so. At least it didn’t work when I tried it myself. 🙂

      You can make the inherited function private in the derived class though, so users of the derived object can’t access the function through the derived class.

      • Reaversword

        True. But trying myself, once deleted a function (is an override/deletion), if you try to use it for the class that deletes it, or derived from this last one, compiler says (in VS2015) something of type: "Function cannot be referenced -- it is a deleted function"

        If I’m not wrong, the difference between use "= delete" and declare it as private in the derived class, is the own derived class isn’t able to access the function (nor give inheritance) in the first case, and in the second case, is able to access to it, but disables inheritance.

  • Aslo

    Finally completed the whole tutorial!

    Thank you for this great experience! I’m considering making a donation when i finally have some money again (currently student…).

    Best regards

  • Salman Sajid

    Do you have any other site on Java programming.. if so.. then please give the link.. if not.. then pls develop a new one.. bcz your tutorial with some exercise is very useful, helpful and easy to understand.. if you make a new site on Java programming.. i believe it’ll be very good for everyone..

  • Lokesh

    Last code example: can’t create constructors with a return type!

  • Thanks for nice tutorial!

    Regarding this:

    Maybe the comment could more accurate saying that: it is a compile error because "void Base::D()" is not virtual (and thus "void Derived::D()" is also not virtual).

    • Alex

      Updated comment to // compile error because Derived::D() does not override Base::D() (because Base::D() is not virtual)

      Thanks for pointing that out!

  • Shereen

    HI Alex, I can not thank you enough for such great tut. You just made my programming experience more enjoyable. Thanks again, and keep the great work up.

  • Jester

    Thanks for the tutorials.
    It helps me allot in learning C++.
    And some advanced concepts of C++ programming than any other tutorials there.
    I think you transfer my programming skills from beginner,
    and now I can call my self intermediate in C++ programming and some other computer knowledge.

    Thank you very much.

  • Sheeplie

    Finished the whole tutorial! Thanks Alex, it has been fun. I’ll definitely be checking back here to refresh on topics as I need them. This was a great introduction to programming in my life. Cheers.

  • Ashoka

    Hello Alex,

    Thank you so much for this great tutorial. I finished it at last. But will be visiting to refresh the knowledge and check for new updates from you.

    Is it possible to provide some functionality to arrange chapters/sections based on the date of modification ? It may help us to check if anything has changed since my last visit 🙂

    • Alex

      Unfortunately I haven’t found an easy way to do this. 🙁 I’ve been updating the front page with new/updated tags whenever I make a substantive change to a lesson, that’s probably your best bet at this point.

  • Ola Sh

    Hello Alex,

    Thanks again for your great tutorials. It made learning C++ easy and fun, something I would not have imagined at first. I will be visiting again for updates and to refresh my knowledge. In the delete section of this lesson, what rule does the compiler follow in converting smaller integral types for the Foo class? Does the compiler apply integral promotion followed by successive numeric promotion, stopping when the new type has a matching constructor? My compiler throws an error stating that more than one constructor matches the argument type. It seems to use integral promotion; however, two constructors with an integral type exist so it throws the error. Thanks for your help. 🙂

    • Alex

      For smaller integral types, the compiler will first try integer promotion, so if your integer constructor is deleted, it will fail. If it can’t find a match, it will try numeric conversion.

  • HattyJetty

    Wow, I’ve managed to get to the end of this wonderful tutorial. I usually get bored very quickly while reading C++ introtuctory stuff, but this source is rather simple and enjoyable, even inspiring. Thanks for your dedicated work! It must be pretty challenging to explain all complexity in such graceful manner. And after nearly 10 years, you still provide all those lessons for free and reply on comments. What a devotion!

  • It is 2016, and these tutorials are still helpful. (Loved the way C++11 stuff was added in the appendix.) Thank you Alex for this wonderful resource. Can we also expect lessons on C++14/17 ?

    • Alex

      As I’ve been rewriting the lessons, I’ve been adding in C++11/14 content, so most of the main tutorial is C++11/14 enabled now (and most of the C++11 appendix is redundant). C++14 actually doesn’t contain that much of interest. I’m curious to see what C++17 holds!

  • ace

    You should add anonymous functions(lambdas) overview, would be nice to learn these.

  • Deondre

    Hey Alex, thanks for taking the time to put together these truly phenomenal tutorials and explanations. I just finished reading through all your lessons (including the featured articles 🙂 ) and I wanted to know what you have planned for the future of this site in terms of new chapters/lessons. If you have any ETA’s for when the new material should be ready that would be great, but if not I understand.

    Thanks again, and hopefully this website can continue to grow and expand as an excellent resource for learning C++.

    • Alex

      I do plan to introduce new material and updates to existing material but I’m a little stalled at the moment due to real-life issues. I’ll get back to it as time permits. Check back periodically -- any new/updated stuff will be noted with a new tag and a date on the front page.

  • SUDARSHAN KOLAR

    Hi Alex… I really liked your tutorials… It was a fun learning experience… I was wondering do you have a website for python as well? If not, can you please suggest me some? Honestly, I tried looking for Python tutorials from you on google…couldn’t find me…

    Thanks again for such an amazing tutorial… you must be a really good teacher…

    Sudarshan

  • maxp

    Thanks Alex, I was able to learn a lot.

  • sigil

    I’d like to join other readers of this tutorial in congratulating the author on his clear, practical and to-the-point piece of work. These texts and examples make much more sense than what you normally find on the net, or even in books.

  • Matt

    Under "override":
    "When this happens, it’s can be easy.."

    "it’s" should be "it".

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter