Reputation: 97
Create an object within a member function Savvas · Lecture 12 · 3 hours ago
Hello to all !
I have a class that takes a struct pointer as an argument. Inside a member function of the class, I am creating a new structure and then I try to call other member functions, thatalso take the structure pointer as an argument. When I hit compile I get a compiler error that tells me: "cannot call member function 'void SearchArray::InsertToTree(Tree*&, int)' (and 'bool SearchArray::IsInTheTree(Tree*, int)') without object". The struct is not part of the class, but even if I make it part of it, I get the same error.
Here is the function:
edit, all the code:
struct Tree{
int item{0};
Tree* left;
Tree* right;
Tree(int val = 0){
item = val;
left = nullptr;
right = nullptr;
}
};
class SearchArray{
public:
void InsertToTree(Tree*& node, int val)
{
if(node == nullptr)
{
node = new Tree(val);
return;
}
else if(val < node->item)
{
InsertToTree(node->left, val);
}
else
{
InsertToTree(node->right, val);
}
}
bool IsInTheTree(Tree* node, int val)
{
if(node == nullptr)
{
return false;
}
else if(val == node->item) { return true; }
else if(val < node->item)
{
return IsInTheTree(node->left, val);
}
else { return IsInTheTree(node->right, val);}
}
static bool Exists(int arr[], int size, int k)
{
Tree* tree = new Tree;
tree = nullptr;
for(int i = 0; i < size; ++i)
{
InsertToTree(tree, arr[i]);
}
bool answer = IsInTheTree(tree,k);
return answer;
delete tree;
}
};
Have I not created an object already? Thank you for your time!
edit: I use eclipse under windows 10 with mingw. I have not tested it with VS.
Upvotes: 0
Views: 559
Reputation: 27577
cannot call member function 'void SearchArray::InsertToTree(Tree*&, int)
This is telling you that InsertToTree()
is a member function of the class SearchArray
. So you'll need to construct an instance of SearchArray
in order to call that member function, something like:
SearchArray mySearchArray; // calls the default constructor, you may need to call a different constructor, i.e. one with arguments
...
for(int i = 0; i < size; ++i)
{
mySearchArray.InsertToTree(tree, arr[i]);
}
and similarilily for SearchArray::IsInTheTree
,
Upvotes: 1