samedi 3 décembre 2022

C++ Primer 5th Ed - Question on accessibility of Derived-to-Base Conversion

In chapter 7 (Object Oriented Programming), below is the excerpts of the author when comes to accessibility of Derived-to-Base Conversion.

Accessibility of Derived-to-Base Conversion
Whether the derived-to-base conversion (§ 15.2.2, p. 597) is accessible depends on which code is trying to use the conversion and may depend on the access specifier used in the derived class’ derivation. Assuming D inherits from B:
• User code may use the derived-to-base conversion only if D inherits publicly from B. User code may not use the conversion if D inherits from B using either protected or private.
• Member functions and friends of D can use the conversion to B regardless of how D inherits from B. The derived-to-base conversion to a direct base class is always accessible to members and friends of a derived class.
• Member functions and friends of classes derived from D may use the derived-tobase conversion if D inherits from B using either public or protected. Such code may not use the conversion if D inherits privately from B.

I don't understand the last 2 bullet points. Seems they are related to each other.
Appreciate any help with examples on it.
Thanks.

Note:
The author is specifically discussing derived-to-base conversion, something that is done outside of the class. Example below from author's excerpts.

class Quote { ... };
class Bulk_quote : public Quote { ... };
:

Quote item;        //  object of base type
Bulk_quote bulk;   //  object of derived type
Quote *p = &item;  //  p points to a Quote object
p = &bulk;         //  p points to the Quote part of bulk
Quote &r = bulk;   //  r bound to the Quote part of bulk

This conversion is often referred to as the derived-to-base conversion. As with any other conversion, the compiler will apply the derived-to-base conversion implicitly (§4.11, p. 159).
The fact that the derived-to-base conversion is implicit means that we can use an object of derived type or a reference to a derived type when a reference to the base type is required. Similarly, we can use a pointer to a derived type where a pointer to the base type is required.

Aucun commentaire:

Enregistrer un commentaire