Initialization and cleanup
I designed my app using Qt Designer. Where should I place the code for initialization and cleanup (best practice)? For example, where should establishing a network connection or database be and where should the clean up for those connections be.
Where they're used.
When acquiring a resource (as a database connection) it a good idea to have that same class manage and free the resource - the ever-so-relevant RAII principle. Basically, every resource that you create and initialize, you free as well. Ordinarily, you wouldn't transfer the ownership of the resource, but there are exceptions. The resource you manage is usually exposed through the class' interface (the methods), so others can manipulate it.
What I was trying to get to is, for example, JSP has jspInit() for initialization and jspDestroy() for clean up. Does Qt have a similar approach to initialize code that will be used through out the life of the program and in different classes? Where should I do final clean up before the program ends?
Does Qt have a similar approach to initialize code that will be used through out the life of the program and in different classes?
Nothing to do with Qt actually. No, there is no special place for that. You initialize in
main(), run your code in
main(), and then clean up in
main(). Or, since you're using an object-oriented language (i.e. C++), you create a few objects in
main()and whatever resources they acquire in their constructors (or along the way), they clean up in the destructors (this is what RAII means). The only thing left to be done in
main()is to clean those few objects if needed.
Where should I do final clean up before the program ends?
Before returning from
Just a small correction, in order to use Qt's features like signals and slots you first need to create an instance of QCoreApplication and for GUI application depending on the type either a QGuiApplication or a QApplication.
Ah, yes, I missed to mentioned that. The first
QObjectone creates should be the root
QObject, that is one of the
QCoreApplicationhierarchy (with some very minor and irrelevant for this discussion exceptions). Still, one does create the application object in