stuff to click

Const return type

difficulty 1 comments 0 added Apr 07, 2011 category c++

From time to time I meet code snippets or get asked about functions returning const type. In 99% of cases that I saw it in code, it was absurd like this:

const int someConst();
const int a = someConst();
int b = someConst();

In both cases someConst() returns anonymous object of type int which can't be modified anyway. It is used for initializing other variables but their constancy does nothing with returning type.

Let's look what options we have to use constants as return type.

Firstly let's consider the types we have in C++:

  • built-in types (bool, char, int...)
  • enumerations
  • arrays
  • pointers
  • references
  • classes

We want constancy of anonymous object returned by a function to make some sense, so built-in types and enumerations are free to go. We can't change anonymous instances of those.

Function can't return arrays, let's exclude them too. If a function returns a pointer, its constancy doesn't make difference as well, what we could do with it? Dereferenced object has nothing to do with constancy of the pointer.

Now consider classes, they may have some member variables and member functions, even const member functions that would run wonderfully on a constant instance of the class. But anonymous instance exists only while the expression it belongs to is evaluated. Why we should care about constancy of this instance? Moreover we may copy-construct or just copy this instance and do the things we want on it. Of course, we can make copy constructor private (the function should be made a member or a friend then) and disable assignment operator but doesn't it compromise the class design? Probably it is possible to find a good example — the life is full of surprises. If you know one that is worth mentioning, please comment.

Regarding pointers and references I'd like to add the following comment. We can use syntax:

const SomeClass*  function1();
const SomeClass&  function2();

these cases although having "const" word in returning type actually returns a pointer to a constant object or a reference to a constant object. In first case we have something real in hands as a return value, it is pointer (not const though). Implementation of reference is based on using unnamed pointer which is dereferenced later. From assembly language point of view these are quite similar. Therefore I wouldn't consider these syntax to be directly related to the subject of the article and using of these constructions is quite frequent.

Curiously, when I wrote

 int & const function(); 

MSVC gave me a warning that "Using qualifiers like const or volatile with C++ references is an outdated practice". I wonder what sense it had in old days?


Place a comment