• Advertisement
Sign in to follow this  

Sharing class objects between files (C++)

This topic is 3821 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok here's the situtation, say I have four files: main.cpp, main.h, physics.cpp and physics.h. I am taking a multithreaded approach so each of the various engines (graphics, physics, etc.) gets their own thread to work in. I am using Boost threads to do this. I tried putting the physicsThread function to be called by Boost in the physics class and setting the new thread to use physicsWorld->physicsThread. The compiler didn't like that (I forget the exact error), so I moved it outside of the class, but still in physics.cpp. However, now it doesn't have access to `this' to do the physicsy stuff it needs to do with physicsWorld. So I tried putting `Physics* physicsWorld' in main.h, so it would be initialized in main.cpp, but still accessible in other source files. However, this causes the linker to complain that physicsWorld is being redefined in every file that includes main.h. So, my question is, how do I access the same class object from multiple files? Cheers.

Share this post


Link to post
Share on other sites
Advertisement
Your design is confused and muddy. Before you try to find language-level tricks to implement it, you should clarify it so that it "just works".

You wish to create a thread which has access to an instance of the physics class, which means that the function executed by the thread must have access to the instance of the physics class in the main thread. This is known as a closure, something which Boost.Thread supports. Problem solved.


Closures are implemented in C++ by creating a functor object which contains a reference to the shared instance that is passed in its constructor and accessed in its operator(). You would typically write code such as:


void run_physics_thread(physics &p)
{
struct functor
{
physics &p;
functor(physics &p) : p(p) {}
void operator()() { p.run(); }
}
ran(p);

boost::function0<void> code = ran;

boost::thread created(code);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement