Re: why creating pointer to reference member is illegal?
blargg.ei3@gishpuppy.com (blargg) wrote:
fabio.lombardelli wrote:
can please somebody explain me why poiter to reference member are
illegal?
I'll show an example:
struct Test
{
Test(int& ref_): ref(ref_) {}
int& ref;
};
int main()
{
int& Test::* ptom = &Test::ref;
}
Amazingly, none of the replies answered your question, because your
question looks like a much more common question. They answered the
following question:
int main()
{
int i;
Test t( &i );
int&* p = &t.ref; // why can't I do this?
}
Now that the wrong question is out of the way, perhaps we can now address
your question of why one can't take a pointer to MEMBER (not object) where
the member is a reference. Just as a refresher, this takes a pointer to
member for a NON-reference type:
typedef int T; // why doesn't this work if changed to int&?
struct X { T i; };
void example( X& x )
{
T X::*mptr = &X::i; // get pointer to member
x.*mptr = 123; // now dereference it on an object
}
Why can't we do the same thing when i is of type int&?
For the same reason this doesn't work.
typedef int& T;
void example( T x )
{
T* p = &x; // get pointer to member
}
And neither works for the exact reason I said earlier, you can only take
pointers to objects and functions... A reference is neither an object or
a function.
If you want to get deeper into the question, the next logical thing to
ask would be, why have a member reference in the first place? References
were not designed to be member variables.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]