Pointer conversions
Conversions (either
implicit or explicit) from a derived class pointer or reference to
a base class pointer or reference must refer unambiguously to the
same accessible base class object. (An accessible
base class is a publicly derived base class that is neither hidden
nor ambiguous in the inheritance hierarchy.) For example:
class W { /* ... */ };
class X : public W { /* ... */ };
class Y : public W { /* ... */ };
class Z : public X, public Y { /* ... */ };
int main ()
{
Z z;
X* xptr = &z; // valid
Y* yptr = &z; // valid
W* wptr = &z; // error, ambiguous reference to class W
// X's W or Y's W ?
}You can use virtual base classes to avoid ambiguous reference. For
example:
class W { /* ... */ };
class X : public virtual W { /* ... */ };
class Y : public virtual W { /* ... */ };
class Z : public X, public Y { /* ... */ };
int main ()
{
Z z;
X* xptr = &z; // valid
Y* yptr = &z; // valid
W* wptr = &z; // valid, W is virtual therefore only one
// W subobject exists
}A pointer to a member of a base class can be converted to a pointer
to a member of a derived class if the following conditions are true:
- The conversion is not ambiguous. The conversion is ambiguous if multiple instances of the base class are in the derived class.
- A pointer to the derived class can be converted to a pointer to the base class. If this is the case, the base class is said to be accessible.
- Member types must match. For example suppose class
Ais a base class of classB. You cannot convert a pointer to member ofAof typeintto a pointer to member of typeBof typefloat. - The base class cannot be virtual.