On 7/16/2015 5:31 PM, fl wrote:
> I have difficulties when reading book "C++ Primer" on derived class section.
> In chapter 15, on OOP, it has a section titled "Conversion to a Reference
> is Not the Same as Converting an Object".
>
>
> "As we've seen, we can pass an object of derived type to a function expecting
> a reference to base. We might therefore think that the object is converted.
> However, that is not what happens. When we pass an object to a function
> expecting a reference, the reference is bound directly to that object.
> Although it appears that we are passing an object, the argument is actually a
> reference to that object. The object itself is not copied and the conversion
> doesn't change the derived-type object in any way. It remains a derived-type
> object".
>
>
> First of all, I am not sure about whether there is a conversion to a reference
> or not from the above. (There is a reference conversion, though not change
> the derived-type object in any way? This sentence is puzzling me a lot.)
A reference to the base class is bound to the area in the object (of the
derived type) that constitutes the base class *subobject*. If you think
of a reference as a kind of a pointer, that pointer points to the
address of the subobject inside that [unchanged] derived class object.
> Then, the following section "Using a Derived Object to Initialize or Assign
> a Base Object" has:
>
> ...
> "Because there is a conversion from reference to derived to reference to base,
> these copy-control members can be used to initialize or assign a base object
> from a derived object:"
>
>
> This paragraph clearly said there is a reference conversion from derived to
> the base. Could you make it clear to me?
Derived class object layout:
[ ... [base class object] ... other base classes and data ]
^
+--- the reference to the derived class object refers to the whole
After "conversion" the reference to the base class object is set to
refer to the portion of the object
[ ... [base class object] ... other base classes and data ]
. ^
. +--- the reference to the base class object refers here
To the code the portion of the [unchanged] *derived* class object is not
"visible". When you manipulate the object using the reference to the
*base* class (object), it only affects the area that represents the base
class object (here inside the derived class object).
I am not sure I made it clearer, so ask more questions if necessary.
V
--
I do not respond to top-posted replies, please don't ask