Sign in to follow this  
Followers 0
jdub

How do I implement the singleton I describe without circular inclusion?

5 posts in this topic

I have a class called 'Window' which essentially contains everything need to run my program.  Inside window, I have 'Simulation', 'Renderer' and 'InputController' classes.  In some instances, these classes need access to a global pointer to a 'Window'.  For example:  I have a DrawDebug() function in 'Renderer' which needs to get information about the status of the Simulation so it can be drawn as text on screen.  I'm not sure exactly how to go about doing this and some help would be much appreciated.  Thanks :)

0

Share this post


Link to post
Share on other sites

Why not just have this

 

 

 
// A function to get access to the singleton at anytime so there is no need for any parameters for the Window class
class Window
{
public:
    static Window* getInstance()
    {
        static Window instance;
        return &instance;
 
    }
};
 
// You can also do it with dynamic memory instead of a static instance, which is preferred.
0

Share this post


Link to post
Share on other sites

Because few people would consider a window to be a good candidate for singleton usage.

0

Share this post


Link to post
Share on other sites

Yes, that looks so wrong. The window would be created at a totally random time or even never if noone asks for the pointer.

And later someone wants two windows...

0

Share this post


Link to post
Share on other sites

Programming is much about keeping the number of dependencies as low as possible. With many dependencies, the source code is difficult to modify. When you find yourself in the situation that you have cyclic dependencies of header files, it is a sign that you may be doing something wrong. Of course, there are valid use cases, but I try to avoid them.

 

In worst case, using header guards, recursion can be avoided at the cost of strange compilation errors.

 

The use of forward declaration may solve this. It is actually a good general principle. Use it wherever possible, so as to avoid including header files.

0

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  
Followers 0