Labelled as homework because this was a question on a midterm I wrote that I don\'t understand the answer to. I was asked to explain the purpose of each const in the follow
const(1) char const(2) * const GetName() { return m_name; } const(3);
const char * const result = aaa.GetNAme();
3 - const method, not allowed to change members nor call any non-const methods.
1 - does not allow to modify inside the pointer, i.e. *result = ..
2 - does not allow to move the pointer, i.e. result = NULL
(1)const char (2)const * (3)const GetName() { return m_name; } (4)const;
As already mentioned in another answers the trick to "remember" it it read from right to left:
last const:
one after last const:
second const:
First:
So to be complete: The function returns a constant pointer (always same location) to a constant char(always same content) and the function does not modify the state of the class.
Take them from the right. The one before the ;
tells the client this is a design level const i.e. it does not alter the state of the object. (Think of this as a read-only method.)
Okay, now the return value:
const char const *const
This is a constant pointer to okay ... here we go boom! You have an extra const
-- a syntax error. The following are equivalent: const T
or T const
. If you take out a const
you get a constant pointer to a constant characters. Does that help?
It is possible that you missed "*" symbol before second const keyword.
const char * const * const GetName() const { return m_name; };
So it means that the function returns constant pointer to constant pointer to constant character.
Given:
const char const * const GetName() const { return m_name; };
The first and second const are equivalent, but only one of them is allowed -- i.e. you can put const
before or after the type (char
in this case) but only one or the other, not both. Either, however, says that the characters pointed to by the pointer cannot be written to.
The const
after the '*' means the pointer returned by the function cannot itself be modified. This is rarely seen on a return type -- what you're returning is a value, which can't be modified in any case (it's normally just assigned to some variable). This can, however, be meaningful in other contexts.
The third const
is only allowed on a member function. It says that when this function is called, the this
pointer that's received will be a T const * const
rather than a T * const
, so the member function can only modify static
or mutable
members of the object, and if it invokes other member functions, they must be const
as well. There is, however, a caveat, that it can also cast away the const'ness, in which case it can modify what it sees fit (with the further caveat that if the object was originally defined as const
, rather than just having a const
pointer to a normal (non-const) object, the results will be undefined).