This topic is now archived and is closed to further replies.


um...external variables in a class?

Recommended Posts

BriarLoDeran    122
Alright, this is my problem. I have the following: The file/variable/function names have been changed to protect the innocent. CHappy.h: #ifndef __CHAPPY_INCLUDED__ #define __CHAPPY_INCLUDED__ class CHappy { // whatever... }; #endif Now in CHappy.cpp, I #include "CHappy.h" and define my functions and such. This is my problem. I want to define a single instance of class and use it for the entire program. What I am currently doing is defining: CHappy *hap = NULL; above my main() and then in any other *.cpp file I just do this: #include "CHappy.h" extern CHappy *hap; My question is thus: Do I have to do it this way? I really want to do it the way iostream.h must defines cout or endl. I want to define it once in CHappy.h and use it for the entire program. I have tried to do the following: in CHappy.h: #ifndef __CHAPPY_INCLUDED__ #define __CHAPPY_INCLUDED__ class CHappy { // whatever... }; static CHappy *hap; #endif This doesn''t work because hap is set to NULL every time CHappy.h is included. I also tried replacing static with extern, but that made numerous linker errors. Well, that is it. Any help would be appreciated! Thanks! Briar->LoDeran();

Share this post

Link to post
Share on other sites
Jumpster    122
class CHAPPY
// dadadada...

class CHAPPY;

#include "GLOBALS.H"
if (HAPPY->issad()) Crybaby->Whaa();

// In main program file...
CHAPPY* HAPPY = new CHAPPY; // Keep this in main. as you have now.


EDIT: Note - GLOBALS.H does not #include "CHAPPY.H"... The class declaration is covered by the forward declaration class CHAPPY;

Edited by - Jumpster on March 14, 2001 10:25:18 PM

Share this post

Link to post
Share on other sites
Liquid    122
Or, better still, do something like this:

in CHappy.h:

class CHappy {
static CHappy* s_pInstance;
static CHappy* GetGlobalInstance();
// rest of your stuff here...

in CHappy.cpp:

CHappy* CHappy::s_pInstance=NULL;

CHappy* CHappy::GetGlobalInstance() {
if(NULL==s_pInstance) {
s_pInstance=new CHappy;
return s_pInstance;

// rest of your implementation stuff goes here...

now, when you want to use your global instance of CHappy, you can do something like this:

CHappy* pHappy=CHappy::GetGlobalInstance();

and you can get rid of all the externs and global variables. Beware that this singleton object (these things are called singletons) cannot be shared across DLL''s without some fiddling, since each DLL would have a seperate copy of CHappy existing in its process space. If you don''t understand any of that, or aren''t using DLL''s, then you don''t need to worry about it.

Hope this helps,


Share this post

Link to post
Share on other sites