Reputation: 3008
I am trying to access awesome
object from another class. I declare this in main()
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QtAwesome* awesome = new QtAwesome(&app);
awesome->initFontAwesome();
app.setWindowIcon(awesome->icon( "clipboard" ));
Login w;
w.show();
return app.exec();
}
Now how do I access awesome
object from Login
or any another class? Is it best to initialize a class in main()
if I want to access from another class?
Upvotes: 1
Views: 75
Reputation: 8560
Declaring awesome
in main() makes it scoped to the main() function, and thus only visible from with main(), or functions you explicitly pass it to from main().
The simple way to achieve what you want is to use an "external variable": Put the definition and declaration outside of the main()
in your main executable file:
main.cpp:
QtAwesome * awesome = new QtAwesome(&app);
int main(int argc, char *argv[]) {
awesome->do_something();
// ...
}
The above is called the defining declaration of "awesome". In other files you want to use awesome in, use the extern
storage specifier:
somerandommodule.cpp:
extern QtAwesome * awesome;
void some_function() {
awesome->do_something();
}
It's important that you have exactly one "defining declaration". The linker will make all extern
awesome declarations point to this one definition.
If you are the one writing the QtAwesome class, another way of doing it is keeping the single instance in the QtAwesome class. This is roughly the "singleton pattern". This just makes it easier to tell where and when initialization is happening:
qtawesome.h:
class Awesome {
private:
static Awesome * singleton;
public:
static Awesome * getInstance() {
if(!Awesome::singleton)
Awesome::singleton = new Awesome();
return Awesome::singleton;
};
};
qtawesome.cpp:
#include "awesome.h"
Awesome* Awesome::singleton = 0;
somerandommodule.cpp:
#include "awesome.h"
void some_function() {
Awesome::getInstance()->do_something();
}
Upvotes: 4
Reputation: 5207
You have two options
pass a pointer or reference to awesome
to the Login
object, e.g. as an argument to the constructor of Login
use a singleton pattern or global variable (as suggested by S.Pinkus)
A global variable or singleton increases the coupling, i.e. the Login
object becomes dependent on this specific QtAwesome
object to exist.
Passing an object into places of usage enables you to use a specific QtAwesome
object for each usage or use the same for multiple usages, etc.
Globally accessible objects, whether global variables or singletons, often make testing more complicated, since the need for such an object is not immediately visible and all tests within the same process access the same globally accessile object, potentially resulting in tests affecting each other in unexpected ways.
Upvotes: 2