I’ve this constructor of a Node class:
Node::Node(int item, Node const * next)
{
this->item = item;
this->next = next;
}
When I compile it gives a compile error: invalid conversion from ‘const Node*’ to ‘Node*’
Is there a way to pass a pointer pointing to constant data?
You’re doing it correctly, but the compiler is right to complain: you’re assigning a “pointer to a const
Node” to a variable with a type of “pointer to a non-constNode“. If you later modifythis->next, you’re violating the contract of “I will not modify the variable pointed to bynext.The easy fix is just to declare
nextas a pointer to non-const data. If the variablethis->nextwill truly never be modified for the life of theNodeobject, then you can alternatively declare the class member to be a pointer to aconstobject:Also note the distinction between “pointer to
constdata” and “constpointer to data”. For single-level pointers, there are 4 types of pointers in regards to theirconstness:Note that
const Nodeis the same asNode constat the last level, but the placement ofconstwith regards to the pointer declaration (“*“) is very important.