Error: initialization of non-const reference type
Hi!
I have been thinking about this one the whole night but couldn't figure it out. I guess it was my bad day (or night). :D
So, I have written the following code (it does nothing useful, it is just for the illustration):
Code:
#include <iostream>
using namespace std;
class A {
public:
int* a;
void change(int* & tmp) {a=tmp;}
int* get() {return a;}
};
int main() {
A temp;
int* buff=new int(42);
temp.change(buff);
temp.change(temp.a);
temp.change(temp.get()); //ERROR: Initialization of non-const reference type 'int *&', from rvalue of type 'int *', in passing argument 1 of 'A::change(int *&)'
cout << temp.get() << endl;
cout << temp.a << endl;
return 0;
}
So I need to pass a pointer to a method by reference! It works fine in the line
temp.change(temp.a);
but when I use the get() method instead of just a:
temp.change(temp.get());
I get an error.
Why???? I mean, both temp.a and temp.get() should return the same thing, shouldn't they??? :confused:
Now, I could have solved it by declaring the method A::change like this:
void change(int* const & tmp) {a=tmp;}
BUT I WANT TO BE ABLE TO CHANGE the variable tmp in this method. So the solution with const doesn't work for me.
Any tips, explanations ?
Thank you!