How to pass a constant pointer to a method in a class

12,961

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-const Node". If you later modify this->next, you're violating the contract of "I will not modify the variable pointed to by next.

The easy fix is just to declare next as a pointer to non-const data. If the variable this->next will truly never be modified for the life of the Node object, then you can alternatively declare the class member to be a pointer to a const object:

class Node
{
    ...
    const Node *next;
}:

Also note the distinction between "pointer to const data" and "const pointer to data". For single-level pointers, there are 4 types of pointers in regards to their constness:

Node *ptr;  // Non-constant pointer to non-constant data
Node *const ptr;  // Constant pointer to non-constant data
const Node *ptr;  // Non-constant pointer to constant data
Node const *ptr;  // Same as above
const Node *const ptr;  // Constant pointer to constant data
Node const *const ptr;  // Same as above

Note that const Node is the same as Node const at the last level, but the placement of const with regards to the pointer declaration ("*") is very important.

Share:
12,961
K''
Author by

K''

Updated on June 05, 2022

Comments

  • K''
    K'' almost 2 years

    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?