How and why Qt functions can be overridden

Florian Bruhin me at the-compiler.org
Mon Aug 30 21:23:01 BST 2021


Hey Maurizio,

On Sun, Aug 29, 2021 at 01:31:23AM +0200, Maurizio Berti wrote:
> So, I'd like to ask if anybody can help me shed some light or at least
> point out some resources with a basic explanation about why some functions
> cannot be overridden, both from "choice" (from the Qt and C++ perspective)
> and from "architecture" (due to the sip binding).

As others pointed out already, the most important distinction is whether
it is virtual or not.

If a method isn't virtual, the compiler will know at compile-time which
code will be executed, based on the statically declared type of an
object. So, if there's a:

    QStyledItemDelegate *delegate = new QStyledItemDelegate(...);
    delegate->initStyleOption(...)

and initStyleOption isn't virtual, then it's clear at compile time that
this will run the code in QStyledItemDelegate::initStyleOption, inside
Qt.

If the method *is* virtual, however, the "delegate" could actually be
something different at runtime, say, a MaurizioStyledItemDelegate, and
delegate->initStyleOption(...) could call totally different code (like
PyQt's wrapper class, which then calls into Python).

This, however, requires a little bit of overhead, both in RAM (storing
the location of the overridden methods) and in runtime (indirection for
all virtual method calls).

For a variety of reasons (explicit is better than implicit, and a lot of
things are explicit in C++; performance overhead considerations; maybe C
compatibility), C++ decided to make this opt-in.

You indeed can't do anything about it unfortunately - you could make the
method virtual in Qt if you have a good case for it, but AFAIK that's a
binary incompatible change, so this could only happen for Qt 7.

Here's some more information on those topics:
https://www.geeksforgeeks.org/virtual-functions-and-runtime-polymorphism-in-c-set-1-introduction/
https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c
https://isocpp.org/wiki/faq/virtual-functions

Hope that sheds some light on it!
Florian

-- 
            me at the-compiler.org | https://www.qutebrowser.org 
       https://bruhin.software/ | https://github.com/sponsors/The-Compiler/
       GPG: 916E B0C8 FD55 A072 | https://the-compiler.org/pubkey.asc
             I love long mails! | https://email.is-not-s.ms/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20210830/13343bd4/attachment.sig>


More information about the PyQt mailing list