Udostępnij za pośrednictwem


Pointers to Classes

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

Remarks

The first case is when the specified base class is accessible and the conversion is unambiguous. (See Multiple Base Classes 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 the following figure.

Inheritance Graph for Illustration of Base-Class Accessibility

Inheritance Graph Base-Class Accessibility

The following table shows the base-class accessibility for the situation illustrated in the figure.

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 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 Derived Classes.) It then defines bObject, an object of type B, and two pointers (pA and pB) that point to the object.

// conve__pluslang_Pointers_to_Classes.cpp
// C2039 expected
class A
{
public:
    int AComponent;
    int AMemberFunc();
};

class B : public A
{
public:
    int BComponent;
    int BMemberFunc();
};
int main()
{
   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.

See Also

Reference

Pointer Conversions (C++)