Converting Pointer Types

A pointer to one object type can be explicitly converted to a pointer of another object type. A pointer declared as void * is considered a pointer to any object type.

A pointer to a base class can be explicitly converted to a pointer to a derived class as long as these conditions are met:

  • There is an unambiguous conversion.

  • The base class is not declared as virtual at any point.

Because conversion to type void * can change the representation of an object, there is no guarantee that the conversion type1* void * type2* is equivalent to the conversion type1* type2* (which is a change in value only).

When such a conversion is performed, the result is a pointer to the subobject of the original object representing the base class.

See Derived Classes, for more information about ambiguity and virtual base classes.

C++ allows explicit conversions of pointers to objects or functions to type void *.

Pointers to object types can be explicitly converted to pointers to functions if the function pointer type has enough bits to accommodate the pointer to object type.

A pointer to a const object can be explicitly converted to a pointer not of const type. The result of this conversion points to the original object. An object of const type, or a reference to an object of const type, can be cast to a reference to a type that is not const. The result is a reference to the original object. The original object was probably declared as const because it was to remain constant across the duration of the program. Therefore, an explicit conversion defeats this safety mechanism, allowing modification of such objects. The behavior in such cases is undefined.

A pointer to an object of volatile type can be cast to a pointer to a type that is not volatile. The result of this conversion refers to the original object. Similarly, an object of volatile type can be cast to a reference to a type that is not volatile.

See Also

Reference

Legal Conversions