Pointers to Classes

There are two cases in which a pointer to a class can be converted to a pointer to a base class.

The first case is when the specified base class is accessible and the conversion is unambiguous. (See Multiple Base Classes in Chapter 9 for more information about ambiguous base-class references.)

Whether a base class is accessible depends on the kind of inheritance used in derivation. Consider the inheritance illustrated in Figure 3.1.

Figure 3.1   Inheritance Graph for Illustration of Base-Class Accessibility

Table 3.2 shows the base-class accessibility for the situation illustrated in Figure 3.1.

Table 3.2   Base-Class Accessibility


Type of Function

Derivation
Conversion from
B* to A* Legal?
External (not class-scoped) function Private No
Protected No
Public Yes
B member function (in B scope) Private Yes
Protected Yes
Public Yes
C member function (in C scope) Private No
Protected Yes
Public Yes

The second case in which a pointer to a class can be converted to a pointer to a base class is when you use an explicit type conversion. (See Expressions with Explicit Type Conversions in Chapter 4 for more information about explicit type conversions.)

The result of such a conversion is a pointer to the “subobject,” the portion of the object that is completely described by the base class.

The following code defines two classes, A and B, where B is derived from A. (For more information on inheritance, see Chapter 9, Derived Classes.) It then defines bObject, an object of type B, and two pointers (pA and pB) that point to the object.

class A
{
public:
    int AComponent;
    int AMemberFunc();
};

class B : public A
{
public:
    int BComponent;
    int BMemberFunc();
};
B bObject;
A *pA = &bObject;
B *pB = &bObject;

pA->AMemberFunc();   // OK in class A
pB->AMemberFunc();   // OK: inherited from class A
pA->BMemberFunc();   // Error: not in class A

The pointer pA is of type A *, which can be interpreted as meaning “pointer to an object of type A.” Members of bObject (such as BComponent and BMemberFunc) are unique to type B and are therefore inaccessible through pA. The pA pointer allows access only to those characteristics (member functions and data)  of the object that are defined in class A.