Partager via


Initializing Pointers to const Objects

A pointer to a const object can be initialized with a pointer to an object that is not const, but not vice versa. For example, the following initialization is legal:

Window StandardWindow;
const Window* pStandardWindow( &StandardWindow );

In the preceding code, the pointer pStandardWindow is declared as a pointer to a const object. Although StandardWindow is not declared as const, the declaration is acceptable because it does not allow an object not declared as const access to a const object. The reverse of this is as follows:

const Window StandardWindow;
Window* pStandardWindow( &StandardWindow );

The preceding code explicitly declares StandardWindow as a const object. Initializing the nonconstant pointer pStandardWindow with the address of StandardWindow generates an error because it allows access to the const object through the pointer. That is, it allows removal of the const attribute from the object.

See Also

Reference

Initializers