Reputation: 23
Trying to search for a specific Node in a Tree, and I need to return a pointer to the Node when I've found it. The nodes are of a derived class type called BudgetEnvelope
, and the error that I'm getting reads:
Cannot initialize return object of type
BudgetEnvelope
with an lvalue of typeNode<BudgetEnvelope>
template <class T>
T* Tree<T>::find( Node<T> * ptr, T value){
if(ptr != NULL){
if(ptr->value == value){
return ptr; <------error is on this line
}
else{
if(value < ptr->value){
return find(ptr->left, value);
}
else{
return find(ptr->right, value);
}
}
}
else{
return NULL;
}
}
My understanding was that since the nodes are of the same type as the pointer that I am returning, that it should work. How can I resolve this?
Edit: More information.
When I change the return type to Node<T>*
, the file where I am using this method gives me another error.
void EnvelopeBox::deposit(int id, double amount){
BudgetEnvelope searchKey = *new BudgetEnvelope(id, "searchKey");
BudgetEnvelope* keyPtr = envelopes.find(searchKey); <----same error
keyPtr->deposit(amount);
}
The deposit
method is defined inside the BudgetEnvelope
class, not Node
, so if I change keyPtr
to be the same type Node<T>*
, I can't access the deposit
method.
Upvotes: 1
Views: 589
Reputation: 799
I think you want to return Node<T>*
not T*
because ptr
is of type Node<T>*
e.g.
Node<T>* Tree<T>::find( Node<T> * ptr, T value)
EDIT:
With the new information you provided, what you need to do is convert
BudgetEnvelope* keyPtr = envelopes.find(searchKey);
to
Node<BudgetEnvelope>* keyPtr = envelopes.find(searchKey);
then to access the data inside, you do the following:
BudgetEnvelope myValue = keyPtr->Value;
myValue.deposit(amount)
What you need to do is access the data inside the node.
Alternatively, you can return ptr->Value
from your find
function.
Upvotes: 2
Reputation: 1552
ptr
is a pointer to type Node<T>
and the function returns a pointer to type T
. Types T
and Node<T>
are different.
If you want to return a T*
you should return whatever method in your Node
class returns a pointer to the value contained in that Node
. Otherwise, which i think is what you want, change the signature of T* Tree<T>::find( Node<T> * ptr, T value)
to return Node<T>*
, as Justin suggested.
Upvotes: 2