I'm trying to implement a messaging system, where the header of the message is a scring stored as char *. I'm running into problems when I try to compare it inside individual modules.
-It's not a problem comparing strings, I can compare them just fine inside the class that creates the message.
-I don't think that it's a pointer problem (due to pointers within classes) because the modules can print the string correctly, they just don't compare.
Here's my implementation. Just for reference, I'm using Dev C++ 5 as a compiler.
First we create a simplified version of the message object:
/*
msg.h
This is the message object
*/
#ifndef MSG_H
#define MSG_H
class msg
{
public:
void set(char * in) {head = in;} //put a value to the message
char * get() {return head;} //read the value from the message
private:
char * head; //contents of the message
};
#endif //MSG_H
Then we create a program to use the message object.
In this program, everything works just fine, because it's all kept local.
I did this to prove that the string comparison works.
/*
main.cpp
This creates the message, then tests the header.
As long as I keep it local, it works.
*/
#include <stdio.h>
#include "msg.h"
int main(int argc, char *argv[])
{
msg * a = new msg;
a->set("test");
printf(a->get()); //to prove that it reads the right value
if (a->get() == "test")
{
printf("\n See, it works locally...");
}
}
[flaming] Now we come to the problem.
If I pass the message to another class, the comparisson will no longer work.
Here's the declaration of the class that is supposed to deal with the message:
/*
module.h
This is the module that actually deals with the message
*/
#ifndef MODULE_H
#define MODULE_H
#include "msg.h"
class module
{
public:
void run(msg * message);
};
#endif //MODULE_H
...and the implementation
/*
module.cpp
Implementation of module
*/
#include "module.h"
#include <stdio.h>
void module::run(msg * message)
{
printf(message->get()); //To show that it reads the right value
if(message->get() == "test") //this is the part that doesn't work
{
printf("\n This should show up...");
}
}
Finally, we need to modify the main program to use the class:
(Replace the existing main)
/*
main.cpp
This creates the message, then tests the header.
As soon as I move into a different class, it stops working.
*/
#include "module.h"
//We don't need to include msg.h, as it's included in module.h
int main(int argc, char *argv[])
{
msg * a = new msg;
a->set("test");
//I'm using pointers because that's how it'll need to work in the final program
module * b = new module;
b->run(a);
//clean up
delete a;
delete b;
}
I hope this isn't too complicated... any ideas?