8

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();
}
Georg Fritzsche
  • 93,086
  • 26
  • 183
  • 232
Regof
  • 2,487
  • 3
  • 19
  • 20
  • I guess singelton design pattern is a good point to start with http://stackoverflow.com/questions/1008019/c-singleton-design-pattern – Artem Barger May 09 '10 at 18:13
  • @Artem - to reemphasize what @gf says - don't do this! Global state makes code impossible to compose and tightly coupled. This is bad , amongst other reasons, because it makes it virtually impossible to test. Also, nearly every singleton implementation I have seen was not thread safe in some subtle and unpleasant way you don't notice until your code runs on a CPU with a weak memory model. – Stewart May 09 '10 at 18:35

2 Answers2

8

You probably really do not want to do this, but if you must - in the file that contains main:

#include "A.h"
A a;

int main() {
 ...
}

and then in the files that need to access the global:

#include "A.h" 
extern A a;

You will need to put the declaration of A in the A.h header file in order for this to work.

  • Thanks, will the externs be visible from inside the other classes? – Regof May 09 '10 at 18:19
  • 1
    @Regof If something is declared at file scope (to use an old term) and is not tagged as static, it can be accessed from _anywhere_. That's why creating such objects is A Bad Idea. I would never create such things in my own code, and I suggest you don't either. But the language, as I've indicated, does allow it. –  May 09 '10 at 18:25
  • let me try it out... thats just for an experiment, just playing around, dont worry :-) – Regof May 09 '10 at 18:49
1

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.

Community
  • 1
  • 1
  • 7
    Can'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. – GManNickG May 09 '10 at 21:24