Search code examples
c++staticconstantsqualifiers

c++ - difference between const and static keyword in function header


Consider the following code:

class Test
{
public:
   //1
   int kon1() const;

   //2
   const int kon2();

   //3
   static int kon3();
};

As far as I know, the difference between function 1 and 2 is that :

  1. Function 1 says that the function will not be able to change any data member's value
  2. Function 2 says that it will return a const int

(If I have wrong understanding, please correct me)

My question is : As we can see there, if we want to make a function to be const function, the const keyword is placed behind. But why in function 3, the static function, the static keyword is placed in front?


Solution

  • For const member functions must have the const keyword afterwards to avoid ambiguity with the return type.

    For static, virtual and other keywords having a dramatic effect on how the function works, it's desirable to list it first so it's easier to see in the class definition. For example, we can quickly scan through a list of member functions and spot all the static functions, or all the virtual ones - aiding our understanding of the overall use of the function.

    Marking a member function const (or e.g. an override) is a less crucial distinction - if you have a non-const object you can invoke functions whether they're const or not, the appropriate const-ness is often obvious to the reading developer as they absorb the function return type and identifier, and in some corporate/project coding standards mutating functions are grouped above const-accessors, or const and non-const versions of the same member function are side by side to emphasise their similarities - then the differet const-ness stands out more.

    All these factors combine to make the actual choices in C++ optimal for development, but you're right in observing that they're a bit inconsistent.