Does
const char * const getName () const
{
return name ;
}
means that getName() returns a constant pointer to a constant character? Since the function is constant , it would not modify any of its arguments.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your example,
most likely returns a constant pointer to a constant nullterminated character string (i.e. to the first character in such a string). Technically it’s just a pointer to a
char. But such pointers are treated as pointers to nullterminated strings by e.g.cout.Since the method is declared
constit cannot directly modify ordinary non-mutablemembers, but it can modify data pointed to by members that are pointers. This means that technically it can modify things that are regarded as parts of the object that it’s called on, if those things are declaredmutableor are pointed to by pointers. However, the common convention for aconstmethod is that even if it does some internal changes such as updating a cache, it will not change the object’s externally visible state, i.e. from an outside view it will not appear to have changed the object.For C++,
Preferentially use a string class such as
std::string, in particular to avoid problems with lifetime management of dynamically allocated memory.Don’t use
getprefixes, since in C++ they only add more to read (e.g., would you writegetSin(x)*getCos(x)?). More generally, name things such that the calling code reads like English prose! 🙂 You may look at it as designing a little language.As a general rule, don’t add
conston the top level of a return value, since that prevents move optimizations.Also, conventionally one uses a member naming convention such as
name_(note that the underscore is at the end, not at the front, to avoid conflict with a C naming convention) ormyName.Thus, ordinary in C++ that function would be coded up as
assuming that
stringis available unqualified in the non-global namespace where this definition resides (which is my preference).