Re: Class member acces through pointer vs object
Rahul ha scritto:
{ Multi-posted to [comp.lang.c++]. -mod }
While reading Inside the C++ object model I came through the
following
paragraph
Point3d origin, *ptr = &origin;
A) origin.x = 0.0;
B) ptr->x = 0.0;
The book says "A & B statements performs equivalently if x is a
member
of a struct, class, single inheritance hierarchy, or multiple
inheritance hierarchy" This is because compiler knows the offset of
the member at compile time.
My doubt is, How can the compiler know the offset of x in case of B
for multiple inheritance.
suppose we have
class Base_1{public: int i;}
class Base_2{public: int x;}
class Derived: public Base_1, public Base_2: {public: int k;}
now the offset of x will be different in Base_2 and Derived, and the
ptr may refer to any kind of object at run time, so how can we know
the offset at compile time.
When speaking of offsets, you must be very clear on one point: offset
relative *to which address*?
Let pd be a Derived* pointing to an object of class Derived and you
write pd->x. Is the offset of x relative to pd known to the compiler?
Yes, because the compiler knows the exact layout of class Derived. The
fact that subobject Base_2::x is inside a base class, does not prevent
the compiler to know the offset at compile-time. Notice that all the
compiler needs to know is the *static type* of the pointer, that is
Derived*, which is known at compile-time.
Now, let's write:
Base_2* pb2 = pd;
and consider pb2->x. Is the offset of x relative to pb2 known to the
compiler? The answer is still yes, for the same reasons as above. Even
in this case it's the static type of the pointer, that is Base_2*, that
counts.
You might say: how could it be? how could the offset be known in both
cases? The answer is simple: pd and pb2 do not hold the same address!
When you assign pd to pb2, pb2 receives the address of the Base_2
subobject of *pd which, because of the multiple inheritance, is
different from the address of the whole ("most derived" in standardese)
object *pd.
You can see this by printing the values of static_cast<void*>(pd) and
static_cast<void*>(pb2), they will be different.
I mean the access through pointer must be slower in the above case of
Multiple inheritance. Please correct me if I am wrong.
Access will not be slower. The cost of multiple inheritance is all
confined in the implicit conversion between Derived* and Base_2*
performed by the assignment, because such conversion requires adjusting
the address.
HTH,
Ganesh
PS: Exercise for the reader: if pd and pb2 hold different addresses, how
could it be that the expression "pd == pb2" evaluates to true?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]