um...external variables in a class?

Started by
1 comment, last by BriarLoDeran 23 years, 1 month ago
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();
Advertisement
// In CHAPPY.H
class CHAPPY
{
// dadadada...
};


// In GLOBALS.H
class CHAPPY;
extern CHAPPY* HAPPY;


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


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

Regards,
Jumpster

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
Regards,JumpsterSemper Fi
Or, better still, do something like this:

in CHappy.h:

class CHappy {
private:
static CHappy* s_pInstance;
public:
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,

Liquid

This topic is closed to new replies.

Advertisement