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

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

  • 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.

  • 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.

  • 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.

  • 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.

  • 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!

  • Lokesh

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

  • 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..

  • 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

  • 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.

  • 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."

  • Fabrice Dai

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

  • Wayne

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

  • Mickey

    Thanks for the tutorials.

  • mona

    the best site to learn cpp…thanx a lot

  • 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…

  • Samir

    Bright tutorial. Thank you much Alex.

  • 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.

  • 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 🙂

  • 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

  • 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.

  • waowao fantastic learn source file!

  • 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. 🙁

  • Hashir

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

  • Anvi

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

  • Radu

    Registered to say thanks. This helped…a lot.

    So…thanks!

  • 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
    };

  • 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.

  • 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.

  • I was wondering the same thing

  • ratsby

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

Leave a Comment

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