Reference is supposed to be another name of an object. In order for that
object to have a name it must be an "l-value". So what is l-value? Well, in
the statement below:
int phone_number = 21223345;
string my_address = get_my_new_address("my name is ben");
phone_number and my_address are an l-values (left values); 21223345 and
get_my_new_address("my name is ben") are r-values (right values). A variable
can be bound to either an l-value or an r-value. But as with references,
they can only be bound to an l-value. Why? Simply think that an r-value
doesn't have a name. Consider:
int num = 2;
int& ref_to_num = number; // OK, now ref_to_num is just another name of
num
int& ref_to_oops = 2; // Error, ref_to_oops is just another name
of...er...em...nothing! It can't be done!
ref_to_num = 2; // OK, same as num = 2;
why must have a name? Consider:
fruit& apple = fruit();
Well, if the above example works, then apple will reference to a temporary
object fruit(), which will be destroyed at the end of the statement. And the
subsequent use of apple will be catastrophic!
So a workaround of what you want to do might be:
class A
{
static string default_str;
void f(string& str = default_str); // default_str is an l-value
};
string A::default_str = "";
Regards,
Ben
"sam" <ro**@localhost.com> wrote in message
news:d6***********@news.hgc.com.hk...
Achintya wrote:
sam wrote:
Hi,
I m wondering why I can't declare reference variable for default
value
in a function argument variable?
eg.
class A
{
void f(string &str="");
};
This causes compiled time error.
Sam.
Hi,
You cannot declare a non-const reference to non-lvalue. The "string"
that you are tring to declare doesn't have a l-value for the reference
to get associated with. Hence...
void f(const string& str="");
Sorry, I m a bit confused with this. Why const string& works and string&
doesn't?
Sam.
will work fine in VC++ 6.0
-vs_p...