0

Imagine this simple code, why does it get compile error?

#include <iostream>
using namespace std;

class foo{
public:
    int *b;
    foo(int a) {
        b = NULL;
    }
};

void bar(foo *&a) {
    cout << "OK?" << endl;
}

int main() {
    foo a(2);
    bar(&a);
    return 0;
}

I know I can use bar(foo *a) but why with & symbol it doesn't work and how can I make it work?

Bat
  • 771
  • 11
  • 29
  • 3
    The compiler error is quite explicit as to *why* (the rvalue is from `&a`). But what do you mean by "make it work"? What do you want to achieve? – juanchopanza Mar 08 '16 at 21:04
  • what adjustment should I do in my code so that it won't get compilation-error? @juanchopanza – Bat Mar 08 '16 at 21:07
  • @Bat you answered your own question (one way to make it work is to use `bar(foo *a)`) – M.M Mar 08 '16 at 21:23

1 Answers1

2

To make it work, change main to:

foo *p = &a;
bar(p);

The use of an lvalue reference (foo* &) means that the argument must be an lvalue. p is an lvalue because it is the name of a variable. &a is a prvalue.


If you want to change bar but not main then you could use any of foo *a, foo * const &a, or foo * && a, which can be initialized with an rvalue.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Do you think "lvalue"/"prvalue" is going to mean much to the OP? – Lightness Races in Orbit Mar 08 '16 at 22:30
  • @BarryTheHatchet if it doesn't, they can read [this post](http://stackoverflow.com/a/3601748/1505939) or whatever. It's not really possible to provide a short but complete summary . – M.M Mar 09 '16 at 00:31