class problems

First I have three files. TreeNode.h, TreeNode.cpp, and animalGame.cpp. In animalGame I ask to get the item from a class instance of TreeNode named root. However it throws an error of "request for member 'getItem' in 'root', which is of non-class type 'TreeNode*'" I'm confused as I clearly declared it as a TreeNode 4 lines above. Can anyone help as to why this error is appearing?
Here is the code (snippets)
""""""""""""AnimalGame.cpp""""""""""""""

TreeNode *root = new TreeNode("Penguin");
while (true){
startStatement();
question();
cout << root.getItem() << endl;


"""""""""TreeNode.cpp""""""""

TreeNode::TreeNode(string item, TreeNode* left, TreeNode* right){
item_ = item;
left_ = left;
right_ = right;
}

string TreeNode::getItem(){
return this->item_;
}

"""""""""""'TreeNode.h"""""""""""
public:
TreeNode(string item, TreeNode* left = NULL, TreeNode* right = NULL);
TreeNode(const TreeNode &source);
~TreeNode();
string getItem();
TreeNode* getRight();
TreeNode* getLeft();

private:
string item_;
TreeNode *left_;
TreeNode *right_;
};

for this function you don't need a this pointer reference, since it is part of the class.

Yours:
1
2
3
4
string TreeNode::getItem()
{
      return this->item_;
}


Should be:
1
2
3
4
string TreeNode::getItem()
{
     return item_;
}


Other change:
 
cout << root.getItem() << endl;


should look like:
 
cout << root->getItem() << endl;
Last edited on
See that's the code I had before. I changed it to what you wrote and now it's giving me this error: "multiple definition of `TreeNode::TreeNode(std::string, TreeNode*, TreeNode*)"
I finally got it working...I'm not sure why it works now but I got rid of the TreeNode.cpp file and put the implementation into the header.
"""""""""""""""TreeNode.h"""""""""""""""
class TreeNode{

public:
TreeNode(string item, TreeNode* left = NULL, TreeNode* right = NULL);
TreeNode(const TreeNode &source);
~TreeNode();
string getItem() {return item_;}
TreeNode* getRight() {return right_;}
TreeNode* getLeft() {return left_;}

private:
string item_;
TreeNode* left_;
TreeNode* right_;
};

inline TreeNode::TreeNode(string item, TreeNode* left, TreeNode* right){
item_ = item;
left_ = left;
right_ = right;
}
Probably a fault in your including-order. You should find yourself a tutorial on how to properly split stuff over files and what to include where.

[edit]

Or drop the .cpp files and put everything in headers. It works, but there's probably a good reason not to. Can't think of one though.
Last edited on
Topic archived. No new replies allowed.