"sks" <es******@gmail.comwrote:
i have a problem . consider the following code
class ABC
{
int & r;
public: ABC( int &a) : r(a) {}
};
int main()
{
int d=10;
ABC Myobj(d)
}
i cannot understand how this works and Have two question in my mind
1) we cannot have reference to reference . but here we have a as
refrerence to d and r is reference to a . how is this possible ?
Sure you can have a reference to a reference. What do you think
the following is:
std::cout << a << b << c << d << std::endl;
It's a reference to a reference to a reference to a reference to a
reference to an iostream.
You can chain references as many deep as you want. What really
happens is, all levels in the chain really refer back to the
original item:
int a = 7;
int & b = a; // b refers to a. b -a
int & c = b; // c refers to a. c -b -a
int & d = c; // d refers to a. d -c -b -a
d = 32; // changes a to 32
std::cout << a << std::endl; // prints "32"
2) It is generally known that object is created and then constructor is
called . and references have to be initialised immediately . so my
question since My Obj is created then Constructor is called that means
the object is created in the memory and still the reference is not
initialised . How is this possible ?
I'd say the object is not fully "created" until the constructor
is finished running.
In any case, your code makes me nervous. I don't like objects
that have references in them to a local variable in some function.
If that variable goes out of scope, the reference is now invalid.
In your case, you get away with it only because the variable is in
main().
A reference in an object to a static variable in a function is
safer.
--
Cheers,
Robbie Hatley
East Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
http://home.pacbell.net/earnur/