I m new to c++ programming and i m getting a weird value coming back from a char* variable that i ve set, depending on how i use it. I m obviously doing something really stupid but I can t see the problem. The next couple of paragraphs describe the setup(badly), but it s probably easier to just look at the output and code.
Basically, I have a couple of classes - Menu and MenuItem. The MenuItem class has a name which is of type char*. Depending on how i m using the menu items, i m getting strange results when i do a getName() on the MenuItems.
I have a Machine class which has a state (TestState). This TestState creates a Menu containing MenuItems. When i create a TestState in my main function and have it print out the menu I get what I expect. When i create a Machine which contains a TestState and ask it to print the menu it prints something weird for the name of the root item in the menu.
Output - Last line I m expecting menuItem1 , but i get Hâ∆Hã=ò
Output direct from TestState Object Displaying menu state menuItem1 root not null menuItem1 Output from TestState within Machine Displaying menu state menuItem1 root not null Hâ∆Hã=ò
Here s my code -
Main.cpp
#include "Menu.h"
#include "Machine.h"
#include <iostream>
using namespace std;
Machine m;
TestState t;
int main(void) {
cout << "Output direct from TestState Object" << endl << endl;
t = TestState();
t.print();
cout << endl << endl << "Output from TestState within Machine" << endl << endl;
m = Machine();
m.printCurrentState();
}
Menu.h
#ifndef Menu_h
#define Menu_h
#include <stdlib.h>
class MenuItem {
public:
MenuItem();
MenuItem(const char* itemName);
const char* getName() const ;
protected:
MenuItem *next;
const char* name;
};
class Menu {
public:
Menu(MenuItem *rootItem);
Menu();
void setRoot(MenuItem *r);
MenuItem* getRoot() ;
protected:
MenuItem *root;
};
#endif
Machine.h
#ifndef MACHINE_H_
#define MACHINE_H_
#include "Menu.h"
class TestState;
class Machine;
class TestState {
public:
TestState();
virtual ~TestState();
void print();
protected:
Machine* machine;
MenuItem menuItem1;
Menu menuMain;
};
class Machine {
public:
Machine();
void printCurrentState();
protected:
TestState testState;
};
#endif /* MACHINE_H_ */
Machine.cpp
#include "Machine.h"
#include <iostream>
using namespace std;
TestState::TestState() {
menuItem1 = MenuItem("menuItem1");
menuMain = Menu(&menuItem1);
}
void TestState::print(){
cout << "Displaying menu state " << endl;
cout << menuItem1.getName() << endl;
if (menuMain.getRoot() == NULL) {
cout << "root is null" << endl;
} else {
cout << "root not null " << endl;
cout << menuMain.getRoot()->getName() << endl;
}
}
TestState::~TestState() {
// TODO Auto-generated destructor stub
}
Machine::Machine() {
testState = TestState();
}
void Machine::printCurrentState() {
testState.print();
}
Any help would be appreciated. I m a bit lost. Thanks Dave