Re: trouble assigning reference
Christopher wrote:
I am getting an odd compiler error:
'Pass::operator =' : cannot access private member declared in class
'Pass'
It is speaking as if I am trying to assign a Pass object to Pass
another object, but I am trying to assign a reference to another
reference.
First understand what a reference does: it names an object. Below, the
names foo and bar both name the same int object; there is no difference in
terms of how foo and bar behave in code that uses it within the function:
void f()
{
int foo;
int& bar = foo;
foo = 123; // assigns 123 to int that foo names
bar = 123; // assigns 123 to int that bar names
}
You could even think of every normal variable as really being a reference.
For example, foo above could be internally implemented by an odd compiler
as something like
int __actual_internal_int;
int& foo = __actual_internal_int;
The point is that names in code refer to objects, usually in such a direct
way that you think of the name AS the object, which then makes references
seem like a different thing, even though they are just a way to make this
association mechanism more visible.
So when you say "assign to a reference", you seem to think that bar above
is an object that can be operated on distinctly from the integer it names.
It can't. Just as foo names an int object, and always the same int object
(within a particular ivocation of f()), so does bar, and they both in fact
name the same int object.
So later when you have a reference to an object whose class makes copying
and assignment private, you obviously cannot assign to the object referred
to:
class Noassign {
private:
Noassign& operator = ( Noassign const& );
};
void f()
{
Noassign x;
Noassign& y = x; // reference to what x names
Noassign z;
x = z; // obviously an error
y = z; // error for exact same reason
}
Argh, and now I just remembered that I should first refer one to the FAQ.
Better late than never...
http://www.parashift.com/c++-faq-lite/references.html