override

override and final

Using the context-sensitive keyword override and final, you can explicitly manage the overriding of virtual functions. In particular, the keyword override solves many issues with difficulty finding bugs in object hierarchies: Methods that should override methods of base classes. The result is syntactically but not a semantically correct program. The program performs the wrong stuff in the right way.

 

override

To override a method, the signature of the overriding method has to match precisely. What sounds easy is often not easy in practice: If the method’s signature fits not precisely, you will get the correct program with the wrong behavior. That’s simple; a different method will be invoked.

The name override in the method declaration expresses that the method should override a virtual method of a base class. The compiler checks the assertion. It checks the parameter of the method, the return type of the method, and qualifiers like const and volatile. Of course, the compiler notices if the overridden method is not virtual.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// override.cpp

class Base {

  void func1();
  virtual void func2(float);
  virtual void func3() const;
  virtual long func4(int);

  virtual void f();

};

class Derived: public Base {

  virtual void func1() override;

  virtual void func2(double) override;

  virtual void func3() override;

  virtual int func4(int) override;

  void f() override;

};

int main(){

  Base base;
  Derived derived;

};

 

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    If you compile the program, the compiler will complain a lot. The error message is very specific.

    The compiler complains in line 16 that the method func1 is not overriding a method. The same holds for the func2. It has the wrong parameter type. It goes on with the method func3. func3 has no const qualifier. func4 has the wrong return type. Only method f in line 24 did it right and overrides the method f of their base class.

    .

    override

    It’s a job for final If a virtual method should not be overridden.

    final

    final supports two use cases. First, you can declare a method that can not be overridden; second, you can define a class from which you can not derive. The compiler uses the same rules as in the case of override to determine if a method overrides a method of a base class. Of course, the strategy goes the other way around because the final should suppress the overriding of a method. Therefore, the compiler checks the parameter of the method, their return type, and the const/volatile qualifiers.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    // final.cpp
    
    class Base {
      virtual void h(int) final;
      virtual void g(long int);
    };
    
    class Derived: public Base {
      virtual void h(int);
      virtual void h(double);
      virtual void g(long int) final;
    };
    
    class DerivedDerived: public Derived {
      virtual void g(long int);
    };
    
    struct FinalClass final { };
    struct DerivedClass: FinalClass { };
    
    int main(){
    
      Base base;
      Derived derived;
      DerivedDerived derivedDerived;
    
      FinalClass finalClass;
      DerivedClass derivedClass;
    
    };
    

     

    What’s happening at compile time?

    The compiler does its job very neatly. It complains that the method h in the class Base (line 4) is overridden by the method in class Derived (line 9). Of course, it’s okay that the method h (line 10) in class Derived overloads f for the parameter type double. The method g (line 11) in the class Derived is quite interesting. The method overrides method g (line 5) of the class Base and declares the method final. Therefore, g can not be overridden in DerivedDerived (line 15).

    To the class FinalClass (line 18). DerivedClass can not be derived from FinalClass, because the BaseClass is final.

    final

     

    I intentionally ignored one fact. The keywords override and final are context-sensitive keywords. What does that mean?

    Context-sensitive keywords

    override and final are only keywords in specific contexts. These contexts are the declaration of a method or a class. If you use them in other contexts, they will be identifiers. What was the reason for introducing context-sensitive keywords into the C++ standard? On the one hand, the C++ standardization committee doesn’t like it introducing new keywords; on the other hand, the classical programs keep valid if they use the context-sensitive keywords override and final. With classical programs, I mean a program written with C++98/C++03 syntax in mind.

    Context-sensitive keywords following a key principle of C++: Don’t break existing code.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // keywords.cpp
    
    #include <iostream>
    
    void override(){ std::cout << "override" << std::endl; }
    
    int main(){
    
      std::cout << std::endl;
    
      override();
      
      auto final(2011);
      std::cout << "final: " << final << std::endl;
    
      std::cout << std::endl;
    
    }
    

     

    My small program is valid C++, although I named the function override (line 5) and gave the variable the name final (line 13).

    keywords

    Only for the sake of completeness. C++11 has with default and delete additional context-sensitive keywords.

    What’s next?

    The new keyword nullptr defines a null pointer constant in C++11. nullptr clears the ambiguity of the number 0 in C++ and the macro NULL in C. How? You have to wait for the next post.

     

     

     

     

     

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *