Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding errors in functions with pointer parameters

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?

like image 200
Vishal Mahavar Avatar asked Sep 26 '26 10:09

Vishal Mahavar


2 Answers

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

like image 101
songyuanyao Avatar answered Sep 29 '26 02:09

songyuanyao


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 ]
like image 39
Andreas DM Avatar answered Sep 29 '26 00:09

Andreas DM



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!