P
Paul N
I was under the impression that a reference had to be of exactly the
same type as the thing it was a reference to. See for instance FAQ
8.1, which states emphatically "please do not think of a reference as
a funny looking pointer to an object. A reference is the object. It is
not a pointer to the object, nor a copy of the object. It is the
object."
However, a couple of posts recently have suggested that it is all
right for a reference of one type to point to an object of a derived
type. I assumed at first that these were mistaken but I have tried it
out on both Turbo C++ and VC++ and it seems to work. For instance:
#include <stdio.h>
class Base { int a; };
class Derived : public Base { int b; };
int main(void) {
Derived d;
Base& br = d;
printf("Size of Base %d, Derived %d, d %d, br %d\n",
(int) sizeof(Base),
(int) sizeof(Derived),
(int) sizeof(d),
(int) sizeof(br));
}
This gives br having a size of 2, but d having a size of 4. Surely
these things can't be the same?
I could understand it if a reference were simply a funny-looking
pointer, but the FAQ teaches strongly against this. How can things be
the same if they're different?
Thanks for any explanation.
Paul.
same type as the thing it was a reference to. See for instance FAQ
8.1, which states emphatically "please do not think of a reference as
a funny looking pointer to an object. A reference is the object. It is
not a pointer to the object, nor a copy of the object. It is the
object."
However, a couple of posts recently have suggested that it is all
right for a reference of one type to point to an object of a derived
type. I assumed at first that these were mistaken but I have tried it
out on both Turbo C++ and VC++ and it seems to work. For instance:
#include <stdio.h>
class Base { int a; };
class Derived : public Base { int b; };
int main(void) {
Derived d;
Base& br = d;
printf("Size of Base %d, Derived %d, d %d, br %d\n",
(int) sizeof(Base),
(int) sizeof(Derived),
(int) sizeof(d),
(int) sizeof(br));
}
This gives br having a size of 2, but d having a size of 4. Surely
these things can't be the same?
I could understand it if a reference were simply a funny-looking
pointer, but the FAQ teaches strongly against this. How can things be
the same if they're different?
Thanks for any explanation.
Paul.