Mutual inclusion with singleton - c++

I currently have a problem with mutual inclusion in a project of mine (C++).
Normally, if I had a mutual inclusion problem, I'd easily solve it by either forward declaration or redesigning the classes a bit. But this time, I'm stuck:
I have a class called Game, which creates and launches core game systems, where one of these is called GraphicsSystem.
In the Game constructor, a GraphicsSystem object is dynamically created and stored in a GraphicsSystem* pointer. Looks like this:
Game::Game ()
{
gfxSys = new GraphicsSystem(80, new Camera());
}
Now my GraphicsSystem class needs to access a Game class's method at one point to get the player object, which is stored within the Game object. The respective part looks like this (Game is btw a singleton!):
void GraphicsSystem::handleFrame ()
{
ElementList elements = Game::instance()->getPlayer()->getEnvironment()->getElements();
}
Now I tried forward declaration in both directions already, but that wouldn't satisfy the compiler. I could of course also just put the player pointer into the graphics system, but I really don't want to do that, since he doesn't belong there.
Is there any way to resolve this without me having to change the design too much? I'm really stumped right now, so I hope you guys can help me.
I'm using Visual Studio 2010 (Visual C++).
Thank you in advance!
Chris

Forward declare GraphicsSystem in Game.h. Include Game.h in GraphicsSystem.h if it needs it. Include Game.h and GraphicsSystem.h in Game.cpp. Include Game.h and GraphicsSystem.h in GraphicsSystem.cpp.
That should work based off the code you posted.

There are two main ways to break circular dependencies in C++.
1) Create a 'interface' class which lists the methods implemented by your real class and which your real class inherits from. Then you can include that instead of the declaration of the real class.
2) Pimpl - a class holds an opaque pointer to its real data, solving the problem of having to include declarations for the types of member variables.

I know this is going to sound dodgy, but have you considered holding a global reference to the initialized Game class?
I know globals are evil and so on and so forth, and I'm sure lots of people are going to rage, but in my personal experience I have succumb to Singletonitis with the Game class (among others) and found that sometimes it just simply isn't necessary.
The biggest question you need to ask yourself is "Who are you trying to protect your Game object from? and is there any reason why you need to request an instance each time you need the game class? I'm pretty sure that if your Game object wasn't initialized, you wouldn't be doing much else in your engine anyway.
Hope this might help you think about things in a different way, even though it's not answering your question directly.

Related

Why can a user change from private to public?

I've made a programm with libraries.
One library has a interface for to include a header for an extern programm call:
class IDA{
private:
class IDA_A;
IDA_A *p_IDA_A;
public:
IDA();
~IDA();
void A_Function(const char *A_String);
};
Then I opened the header with Kate and placed
class IDA_A;
IDA_A *p_IDA_A;
into the public part.
And this worked?! But why? And can I avoid that?
Greeting
Earlybite
And this worked?!
Yes
But why?
private, protected and public are just hints to the C+++ compiler how the data structure is supposed to be used. The C++ compiler will error out if piece of C++ source doesn't follow this, but that's it.
It has no effect whatsoever on the memory layout. In particular the C++ standard mandates, that member variables of a class must be laid out in memory in the order they are declared in the class definition.
And can I avoid that?
No. In the same way you can not avoid, that some other piece of code static_casts a (opaque) pointer to your class to char* and dumps it out to a file as is, completely with vtable and everything.
If you really want to avoid the user of a library to "look inside" you must give them some handle value and internally use a map (std::map or similar) to look up the actual instance from the handle value. I do this in some of the libraries I develop, for robustness reasons, but also because some of the programming environments there are bindings for don't deal properly with pointers.
Of course this works. The whole private-public stuff is only checked by the compiler. There are no runtime-checks for this. If the library is already compiled, the user only needs the library file (shared object) and the header files for development. If you afterwards change the header file in the pattern you mentioned, IDA_A is considered public by the compiler.
How can you avoid that? There is no way for this. If another user changes your headerfile, you can do nothing about it. Also is the question: Why bother with it? It can have very ugly side-effects if the headerfile for an already compiled lib is been changed. So the one who changes it also has to deal with the issues. There is just some stuff you dont do. One of them is moving stuff in headers around for libraries (unless you are currently developing on that library).
You've got access to the p_IDA_A member variable, and this is always possible in the manner you've outlined. But it is of type IDA_A, which for which you only have a declaration, but not the definition. So you can not do anything meaningful with it. (This method of data hiding is called the pimpl idiom).

C++ Class Access Management

I'm developing a game using OpenGL. I have a Game class that contains all the environment variables (by environment, I mean things like gravity or tile sets). There's only one Game object. I also have another class called Entity, which contains properties to display objects on the screen.
I'm finding myself needing access to more and more Game variables in my Entity class. At the moment i'm just using parameters to pass data into each function, but I'm considering just passing a pointer to the Game class? Is there anything wrong with that? Is there a better way?
I think this is good practice. It is good idea to replace a group of parameters with a parameter object.
Just make sure that Game remains cohesive. The variables contained within Game should be related.
Make Entity a Friend of the Game class.
Please see
http://msdn.microsoft.com/en-us/library/465sdshe.aspx
Note: If this is ever done in C#, there isn't a friend keyword or exact equivalent.

Pass an instance to another class and access it c++

I'm simply passing a pointer to an instance of a class to another class but I just can't access anything from the pointer. It's really, really starting to bug me. Here's a really simple example of the code:
//manager.h
Game* game = new Game();
BClass* bc = new BClass(this);
//bclass.h
BClass(Manager* bcref) {
bcref->game //error
bcref->bc //error
}
//The errors are "left of ->x must point to class/struct/union/generic type.
I understand this is because I need to forward declare but adding things such as "class Manager;" at the top doesn't seem to do anything. I still can't access a member or method. I'm really trying to do something that's incredibly simple and I've been pulling my hair out for hours. I've googled and tried pretty much everything I can.
Any ideas?
In order to be able to do this:
BClass* bc = new BClass(this);
Manager needs the definition of BClass. This is presumably in bclass.h. In order to do this
bcref->game;
BClass needs the definition of Manager. This is presumably in manager.h.
So you would need include each header in the other, which would lead to a cyclic include dependency. What you really need to do is break the dependency by moving the implementations to bclass.cpp and manager.cpp respectively, and use only forward declarations in your headers.

Objective-C++: Headers and Class Methods

I've been learning Objective-C for the last few months with the goal of writing iOS games. I want to be able to make the games relatively easy to port to other platforms, so I've also been simultaneously learning C++. My plan is to write most of the game in C++ and write the drawing and game loop in Objective-C. I know (at least I've been told) this is possible, but there are a few things that I'm still confused about.
I'm still pretty new to C++, and coming originally from Java, is it a bad idea to have functions return type be void?
Is there a way to write class functions? ie. className.function(); rather than object.function();
I've never needed header files for my C++ files before. Could someone point me in the direction of an example? Preferably one that has a constructor method? I don't know what to make its return type. (It should be a pointer to the class right?)
I'm going to assume your questions are about how to write C++, as that seems to be what you're asking.
Not at all, void functions are well-accepted in nearly all languages, C++ and Objective-C included. (Though many people prefer returning a bool success/fail value)
You're probably looking for static functions. These don't require instantiation, but there are some limits on their use (see here for more info).
Any non-trivial C++ project should use header files. They serve several purposes, including keeping your code more organized and modular, decreasing compile-time in many cases, and aiding in conceptualizing your design before you think about implementation.
An important thing to note when breaking your class into .h and .cpp files is the use of the scope modifier :: when defining functions. When defining the function public void foo() in your .cpp file, after having declared it in your header, you must use public void ClassName::foo() { }. This is because you defined foo while in the class ClassName { } block in your header, but you are now in the global scope.
(As for your question about C++ constructors, if should be public ClassName::ClassName(); and you don't need to return anything).
Now obviously, many of these points differ in Objective-C. For example, the init method (comparable to the C++ constructor) does, as you said, return a pointer to the object being inited. If you want specific information on writing cross-language apps, you should update your question to be more specific, or open a new question.
No that is fine.
Yes: Assume SomeClass.h:
#pragma once
class SomeClass {
public:
static bool myStaticMethod();
};
and in SomeClass.cpp:
#include "SomeClass.h"
bool SomeClass::myStaticMethod() {
// A static method
return true;
}
See the first part of 2, above.
Some other notes:
A. Change all your Objective-C interface code to Objective-C++ by renaming all the .m files to .mm. This way you can use your C++ code freely.
B. I couldn't think of a B.

Extending an existing class like a namespace (C++)?

I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.