Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 922
K'' Avatar asked Oct 25 '25 13:10

K''


1 Answers

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.

like image 105
Adam Rosenfield Avatar answered Oct 28 '25 02:10

Adam Rosenfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!