Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I get data from the class that instantiated me?

Status
Not open for further replies.

SearchMe

Programmer
Feb 9, 2006
3
US
I'm writing a server that will run in a separate thread. Since I'm using a Thread class, the server is written as a class by itself. However I need for the server to access some of the data that is in the main class.

So I have instantiated the class like so:

ServerThread serv;
in the class definition.

And I thought maybe I'd just write a method of that class I could call to save a pointer to my object, like:

serv.savePontr(this);

However when I attempt to do this I can't seem to get around the catch 22 where I have to include the header from this class in the server code and of course when it sees the ServerThread serv; it isn't defined just yet.

So the question is what's the best way of letting the server get data from the class that instantiated it. I considered a callback, but I have yet to see an example that I could understand well enough to implement.

Thanks,
Jim.
 
If you are only passing a pointer, then you can use a forward declaration in the ServerThread header, and include the Server.h file in the ServerThread.cpp. Inside your Server.h you have to include ServerThread.h since you use an actual object (not a pointer) inside the class. The general look is this:
Code:
// MainClass.h

#ifndef MAIN_CLASS_H
#define MAIN_CLASS_H

#include "OtherClass.h"

class MainClass
{
  // ...
  OtherClass otherClassInst;
};

#endif
Code:
// MainClass.cpp

#include "MainClass.h"
#include "OtherClass.h"

// ...
Code:
// OtherClass.h

#ifndef OTHER_CLASS_H
#define OTHER_CLASS_H

class MainClass;

class OtherClass
{
  // ...
  MainClass* mainClassPtr;
};

#endif
Code:
// OtherClass.cpp

#include "OtherClass.h"
#include "MainClass.h"

// ...
 
Thanks, that works. I thought I'd tried that but it complained about my forward declaration. I erroneously thought it was telling me I couldn't do it, but I guess I had the format of the decl wrong.

Thanks
Jim.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top