C++: Declare a global class and access it from other classes?
24,307
In C++ declaring a global instance of a class is a no-no.
You should instead use the singleton pattern, which gives you a single instance of your object accessible from the entire application.
You can find a lot of literature on C++ singleton implementation, but wikipedia is a good place to start.
Thread safe singleton pattern implementation has already been discussed on stackoverflow.
Related videos on Youtube
Author by
Regof
Updated on May 10, 2020Comments
-
Regof almost 4 years
I have a class which should be declared globally from main() and accessed from other declared classes in the program, how do I do that?
class A{ int i; int value(){ return i;} }; class B{ global A a; //or extern?? int calc(){ return a.value()+10; } } main(){ global A a; B b; cout<<b.calc(); }
-
GManNickG almost 14 yearsCan't use global, so use singleton? What do you think a singleton is? It's global. Just use a global and ditch all the single-instance crap you don't need.
-
mczarnek over 2 yearsThere actually is one very good reason to use Singleton: You don't have to remember to extern the class in every single file you want to use it from. Could lead to weird errors, probably not. But more importantly easier to use the class you've created in larger projects.