1

I am making a VC++ 2008 windows project, and I want to have an object that I instantiate exist for all intense, and purposes globally. this object shall be a timer to monitor how long the program has been running, and needs to be accessible by other objects for the purpose of log file generation. I know that I can mark native, and sudo-native (string) members as extern to make them reachable, but how do I get an object to exist globally to other objects. Do I put the object definition before the class of the object that needs to know of its existence (insuring to load the class first), or must I put a method in my main that allows access to the object?

gardian06
  • 1,236
  • 3
  • 19
  • 34
  • 1
    `sudo` only exists on Unix-like environments. On Windows you need to look at *user account control* (UAC), but you should be *very* careful. I doubt you need that for a simple timer, though. – Kerrek SB Feb 06 '12 at 07:28

2 Answers2

2

Just create a class with the methods you need, then declare an instance of the class global include the header of the class in all your modules where you want to use it plus have an extern declaration telling the modules that the definition is elsewhere. Maybe you have some common header that all include.

extern MyClass yourInstance;

The global definition should be where the main() is

MyClass yourInstance;

or if you prefer allocate it on the heap by using a pointer, then allocate at start of main and delete at end and just have the pointer as global.

that said, it is normally not good to have global declarations instead you should declare the MyClass in the main() and then pass a pointer to it to all functions/classes that you use. that is how i would do it. Then you don't need the extern statement and just include the header MyClass.h

one problem with global instances is that you have little or no control of when they are created/destroyed.

AndersK
  • 33,910
  • 6
  • 56
  • 81
1

What you describe is often done using a singleton.

Here's an example on how to write one: Singleton: How should it be used

Here's another one: Can any one provide me a sample of Singleton in c++?

Also note: What is so bad about singletons?

Community
  • 1
  • 1
Johan Lundberg
  • 23,281
  • 9
  • 67
  • 91