I'm re-learning c++ (I have 10 years Java experience) and I'm also learning Qt in the process...
I'm used to creating objects (in Java) via:
MyObject o = new MyObject();
But when creating a QApplication in c++, the examples simply show:
QApplication app(argc, argv);
app.setOrganizationName("My Company");
app.setApplicationName("The App");
So suddenly, I have a reference to "app" and no obvious (to me) assignment to app...
Is this pattern a c++ thing or specific to Qt? What is this pattern called?
Thanks!
Not really a Qt question but,
//You have an assignment to app
QApplication app(argc, argv);
// is just the same as
QApplication *app = new QApplication(argc, argv);
In C++ you have the choice of creating objects locally (on the stack) or with new (on the heap). Allocating it locally here makes more sense when the app object has a definite lifetime (the length of main) won't be deleted and recreated and only one exists.
One annoying feature of C++ (because of it's c heritage) is that accessing parts of the resulting object is different. If created directly you use "." app.name()
but if allocated with new you need to use 'c' pointer notation app->name()
ps. There are a few Qt specific memory features. Qt does a lot of memory management for you, eg. copy-on-write, automatic delete. In Qt you rarely have to call delete for an object - for a C++ expert these are sometimes annoying but from Java it should look more natural.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With