When writing a code this way...
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node(int data) {
this->data = data;
}
};
void display(const Node* &p){
cout<<p->data<<endl;
}
int main(){
Node *p = new Node(10);
display(p);
return 0;
}
I get the following error.
error: cannot bind non-const lvalue reference of type 'const Node*&' to an rvalue of type 'const Node*'
However, this works if the parameter const Node* &p of function display is changed to Node* &p.
Can someone explain to me how this works?
p is a Node * and can't be bound to const Node* & directly. It needs to be converted to const Node* firstly, which is a temporary, i.e. an rvalue, and can't be bound to lvaue-reference to non-const.
Changing to Node* & fixes the issue, p could be bound to Node* & directly without any implicit conversion.
BTW temporaries could be bound to lvalue-reference to const. Changing parameter type to const Node* const & works fine. LIVE
Or change from pass-by-reference to pass-by-value (the pointer itself) as const Node*. LIVE
const Node* &p
// p is a reference to a pointer to a constant 'Node'
And what you have is
Node *p
// ^^ discarding the const qualifier is an error
display(p);
// ^^ error
Probably the easiest fix here is to live up to the promise
const Node *p = new Node(10);
//^^^
display(p); // OK
void display(const Node*& p) is essentially the same as
void display(const Node** p)
And the standard has a good example of why initializing it with a (non-const) Node** is not allowed (n4659 [conv.qual]):
// [ Note: If a program could assign a pointer of type T** to a pointer of type const T** (that is, if line #1
// below were allowed), a program could inadvertently modify a const object (as it is done on line #2). For
// example,
int main() {
const char c = 'c';
char* pc;
const char** pcc = &pc; // #1: not allowed
*pcc = &c;
*pc = 'C'; // #2: modifies a const object
}
// — end note ]
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