Why we need to put const at end of function header but static at first?

with a const instance method such as int get_hours() const;, the const means that the definition of int get_hours() const; will not modify this.

with a static method such as static void fun();, const does not apply because this is not available.

you can access a static method from the class or instance because of its visibility. more specifically, you cannot call instance methods or access instance variables (e.g. x, hours) from the static method because there is not an instance.

class t_classname {
public:
  static void S() { this->x = 1; } // << error. this is not available in static method
  void s() { this->x = 1; } // << ok
  void t() const { this->x = 1; } // << error. cannot change state in const method
  static void U() { t_classname a; a.x = 1; } // << ok to create an instance and use it in a static method
  void v() const { S(); U(); } // << ok. static method is visible to this and does not mutate this.

private:
  int a;
};

The const in the end means the function is constant, so it doesn't change the object's state.

When you put the const in the end, you can't change the state of the object's members.

Declaring a function static means it doesn't belong to the object at all, it belongs to the class type.

Putting const in the beginning means the return type value is a constant.

Tags:

C++