[Development] Should QObject::event() be protected or public?
Marc Mutz
marc.mutz at qt.io
Fri Mar 15 18:51:52 CET 2024
On 15.03.24 18:31, Christian Kandeler via Development wrote:
> On 3/15/24 18:09, Marc Mutz via Development wrote:
>> I like simple rules. "Overrides should have the same access level as the
>> initial virtual function." is a simple rule.
>
> But it makes no sense in general. The base class is the interface, and
> overrides should have the least possible visibility for their purpose.
Let me turn that around and ask you to explain why the specific static
type should matter when calling a virtual function:
MyWidget *myw = new MyWidget; // ¹
QWidget *id = myw;
QObject *obj = wid;
obj->event(e); // OK
wid->event(e); // ERROR: protected
myw-.event(e); // OK, public again
"Normal" functions never behave that way. Why should virtual functions
behave so erratically? Users look at the QObject docs, see that there's a
public event() function and for some reason decide that's the function
to call. QWidget is-a QObject, so by the Liskov Substitution Principle,
you should be able to do anything to a QWidget than you can do to a
QObject. So why can't I call event() on it?
¹ from src/corelib/doc/snippets/events/events.cpp (iow: our docs)
Thanks,
Marc
--
Marc Mutz <marc.mutz at qt.io>
Principal Software Engineer
The Qt Company
Erich-Thilo-Str. 10 12489
Berlin, Germany
www.qt.io
Geschäftsführer: Mika Pälsi, Juha Varelius, Jouni Lintunen
Sitz der Gesellschaft: Berlin,
Registergericht: Amtsgericht Charlottenburg,
HRB 144331 B
More information about the Development
mailing list