Question

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.

Was it helpful?

Solution 2

Your example,

const char * const getName() const { return name; }

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 const it cannot directly modify ordinary non-mutable members, 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 declared mutable or are pointed to by pointers. However, the common convention for a const method 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 get prefixes, since in C++ they only add more to read (e.g., would you write getSin(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 const on 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) or myName.

Thus, ordinary in C++ that function would be coded up as

string name() const { return name_; }

assuming that string is available unqualified in the non-global namespace where this definition resides (which is my preference).

OTHER TIPS

It means that getName() returns a constant pointer to a constant character and it will not modify any non-mutable class members inside the function body.
Note that class members declared as mutable can be still modified in this function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top