Sign in to follow this  

Global classes?

Recommended Posts

My graphics class needs to be accessible for all other classes (they all want to draw stuff) but how do I do that? I think it was some static keyword but I tried to make the class global by putting it before main() but then I got : undeclared identifier In the other classes decleared inside main. How do I make a class global? Or do so that everyone can access it?

Share this post

Link to post
Share on other sites
I'd recommend you pass a pointer to the graphics class as a parameter to your drawing routines, but 'extern' is the keyword you use to make something truely global.

//In a header
extern GraphicsClass my_graphics_class;

//In one source file (and only one)
GraphicsClass my_graphics_class;

Then anyone that wants to use my_graphics_class needs to the include that header file first.

Share this post

Link to post
Share on other sites
However, globals do not belong to the OOP paradigm. A (perhaps) more sophisticated solution is the use of the singleton pattern. Basically it hides the constructor from users while exposing a function that returns (the one) instance of the class. Like this:

class CSingleton

static CSingleton* m_pInstance;

CSingleton( void );


~CSingleton( void );

static CSingleton* GetInstance( void )
if ( !m_pInstance )
m_pInstance = new CSingleton();
return m_pInstance;

See for yourself what you want to do. Greetz,


Share this post

Link to post
Share on other sites
Thats a very nice way to do it, had to read it a couple of times before I understood it though. :P

Thanks, Ill try to use that with my graphic class!

[edit] I triedto implent it, I added the protected stuff to my class:

class SdlHandle {
// singleton pattern
static SdlHandle* m_pInstance;
SdlHandle( RESX, RESY, 32 );

But then I get:

d:\Documents\CPP\Visual Studio Projects\TileSystem\SdlHandle.h(20) : error C2059: syntax error : 'constant'
d:\Documents\CPP\Visual Studio Projects\TileSystem\SdlHandle.h(20) : error C2238: unexpected token(s) preceding ';'
d:\Documents\CPP\Visual Studio Projects\TileSystem\SdlHandle.cpp(3) : error C2511: 'SdlHandle::SdlHandle(int,int,int)' : overloaded member function not found in 'SdlHandle'

Do the constructor need to be (void)? Sdl wants to know which resolution I like... Or should I make functions that can change the resuolution afterwards and let the constrcutor be void?

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this