So I am learning C++ right now, and I just started to get into Pointers, and I thought I would understand the semantics pretty well till iI saw this in one of the recommended solutions to an exercise int the Book I am learning with:
const char* sa = * ( static_cast < const char* const* > (a));
I understand everything aside the const*
in the Type Parameter. Why is it there, what does it do?
EDIT: corrected unclear formulation
*
in a type means that the type is a pointer to the type on the left side of the asterisk.
const
in a type means that the type to the left of const
is constant. For an object, const
means that the value may not be modified. For a reference, const
means that the object may not be modified through the reference.
char
is a type that represents an integer encoded narrow character object.
const char
is a const char
.
const char*
is a pointer to a const char
.
const char* const
is a const
pointer to a const char
.
const char* const*
is a pointer to a const char* const
.
Note that the pointer is indirected:
* ( static_cast < const char* const* > (a));
^ indirection operator
When a pointer is indirected, the result is a reference (lvalue) to the pointed object. If a const char*
were indirected, the resulting lvalue would have the type const char
. Clearly such lvalue couldn't be used to initialize the object const char* sa
.
When a const char* const*
is indirected, the result will be a reference (lvalue) to an object of type const char* const
. Such value can be used to initialize const char* sa
.
A simpler example without casts:
const char c; // c cannot be modified
const char* const a = &c; // a points to charcter object c
// a cannot be modified
const char* sa = *a; // sa points to a as well
sa = nullptr; // sa can be modified; it no longer points to a