Why do Signals have to be public?
-
Ever since I started using the signals-slots mechanism I found it incredibly easy to communicate between objects. However, here are a few questions that I have about this mechanism:
1- Why do Signals have to be public? (Please explain the underlying mechanism)
2- Do slots need to be public as well? (if yes, then why? and if not, then which is better public/private?) -
By emitting a signal object announces change in its state. It doesn't care if anyone is listening and it shouldn't, as it would couple it to that receiver in some way. Private signal would be a mix of concerns. The object is supposed to announce the change. It's not supposed to filter/manage who's able to get the notification. It's the job of the user to make the right connections.
That's the design reason. A technical one is that in Qt4 you made connections only via
SIGNALmacro, which just normalized signal name as a string, so signals could be private. With the function pointer based syntax you wouldn't be able to specify private&Class::signalNamein the staticQObject::connect.Slots are a different story. In Qt5 and 6 you can make a connection to any functor, not just slots. For the purpose of connections slots are pretty much just regular member functions, so they can be public, private or protected like any other method. The only difference is they are registered as slots in meta object and can be used in the old string based connections.
As to which is better - public or private. There's no better or worse. It depends on a use case. Like with regular methods you, as a designer of the class, decide what is the desired access level for given method.
-
Ever since I started using the signals-slots mechanism I found it incredibly easy to communicate between objects. However, here are a few questions that I have about this mechanism:
1- Why do Signals have to be public? (Please explain the underlying mechanism)
2- Do slots need to be public as well? (if yes, then why? and if not, then which is better public/private?)@Saviz said in Why do Signals have to be public?:
1- Why do Signals have to be public? (Please explain the underlying mechanism)
2- Do slots need to be public as well? (if yes, then why? and if not, then which is better public/private?)Treat them as normal functions and you get the answer by yourself.