I got troubles undertanding the following error:
Error 1 error C2440: '=' : cannot convert from 'const X<...> *const ' to 'X<...> *const '
I am trying to use a pointer to const pointer to keep track of a Node during a tree traversal:
bool IsValid() const
{
X* const* previousNode = new X*;
return this->IsValid(previousNode);
}
bool IsValid(X* const* previousNode) const
{
...
if (!*previousNode)
*previousNode = this; // Error
...
return true;
}
Why is this is a const X* const type and cannot be used as a *Const * ?
As the method is a const method, my understanding is that it protects the object itself of being modified. Then why does the compiler try to enforce the constness of a pointer to pointer returning this?
I have not been able to find an answer to this question using the search engine of stack overflow.
Thank you for your answers.
Here is the finale code I finally used if I can be a use for someone:
bool IsValid() const
{
std::unique_ptr<const BST*> previousNode = std::unique_ptr<const BST*>(new const BST*);
*previousNode = nullptr;
return this->IsValid(prevNode);
}
bool IsValid(std::unique_ptr<const BST*>& previousNode) const
{
// Recurse on left child without breaking if not failing
if (this->leftChild &&!this->leftChild->IsValid(previousNode))
return false;
// First node retrieved - assign
if (!*previousNode)
*previousNode = this;
// Previous data does not compare well to the current one - BST not valid
else if (!Compare()((*previousNode)->data, this->data))
return false;
// Set current node
*previousNode = this;
// Recurse on right child
if (this->rightChild && !this->rightChild->IsValid(previousNode))
return false;
return true;
}
Just playing with template and simple data structure. Thank you for your answers.
Let's start simple:
const X* is a pointer to a constant Xconst X* const is a constant pointer to a constant Xconst X* const*is a pointer to a constant pointer to a constant Back to your problem:
X* const* previousNode is a pointer to a constant pointer to an X*previousNode is a constant pointer to an X*previousNode = ... tries to assign something to this constant pointer. It's not possible, the pointer is constant ! The signature of the IsValid method specifies (by using const), that this is a constant object, i.e. its type is const X*. Changing the type of previousNode to const X** should solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With