C ++: declare a global class and access it from other classes?

I have a class that must be declared globally from main () and is accessible from other declared classes in the program, how to do this?

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(); } 
+6
c ++
source share
2 answers

You probably don't really want to do this, but if you should, in the file that contains main:

 #include "Ah" A a; int main() { ... } 

and then in the files that should access the global:

 #include "Ah" extern A a; 

You will need to place declaration A in the header file Ah for this to work.

+7
source share

In C ++, declaring a global instance of a class is no-no.

Instead, you should use the singleton template, which gives you one instance of your object, accessible from the entire application.

You can find a lot of literature on implementing a singleton C ++, but wikipedia is a good place to start.

The implementation of a singleton streaming template has already been discussed in stackoverflow.

+1
source share

All Articles