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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calling a function from outside main

Status
Not open for further replies.

tewari68

Programmer
Jan 25, 2005
87
US
Hi,
I have a general utility header file utility.h, in which I have defined a debug routine

void debug(int debugLevel, const char * debugDesc, const char * debugStr)

I have two more files a.cpp(a.h) and b.cpp (b.h),when I call the debug routine from inside a.cpp(int main) it works fine however if I call some function in b.cpp from a.cpp and call the debug routine from inside that function in b.cpp, I don't see any debug output, though the program compiles fine and is getting all the variables correctly.
Code:
a.cpp

int main(int argv, char * argc[]) {
//create utility Object
utility utilityObj;
utilityObj.debug(1, "U R here", ""); -----> works fine
utilityObj.debug(1, "Creating LogMsg object in main()", "LogMsg logmsg");
         LogMsg logmsg;
logmsg.updateDatabase(To,From, getDateTime) ----> function in b.cpp
                                
}
b.cpp
Code:
void LogMsg::updateDatabase(string To, string From, string getDateTime)
{
//create utility Object
utility utilityObj
utilityObj.debug(1, "you are inside logmsg routine", ""); ---> this call to debug routine does not give any output
}
Appreciate if anybody can help me in this.

Thanks,
Tewari
 
You need to use the same utility object: something like a singleton. You can do this either by declaring a singleton in utility or by inheriting from utility eg
Code:
// The header
class SingleU: public utility
{
public:
   static utility* Self ()
};

// The code
utility* SingleU::Self ()
{
   static utility me;
   return &me;
}

// In a.cpp
int main(int argv, char * argc[]) {
   //create utility Object
   utility* utilityObj = SingleU::Self ();
   utilityObj->debug(1, "U R here", "");
   utilityObj->debug(1, "Creating LogMsg object in main()", "LogMsg logmsg");
   LogMsg logmsg;
   logmsg.updateDatabase(To,From, getDateTime);
   return 0;
}

// In b.cpp
void LogMsg::updateDatabase(string To, string From, string getDateTime)
{
//create utility Object
utility* utilityObj = SingleU::Self ();
utilityObj->debug(1, "you are inside logmsg routine", ""); 
}
It would be more efficient if you passed the parameters of updateDatabase as const string& otherwise it goes through 3 constructors and 3 destructors every time you call it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top