OOPortal OOPortal


C++ Class Construct  «Prev  Next»
Lesson 11Implementation of static/const member functions
Objectiveconst and static member function implementation

static and const Member Functions in C++

The const and static member function implementation can be understood in terms of this pointer access.
An ordinary member function invoked as

x.mem(i, j, k);

has an explicit argument list i, j, k and an implicit argument list that are the members of x.
The implicit arguments can be thought of as a list of arguments accessible through the this pointer.
In contrast, a static member function cannot access any of the members using the this pointer. A const member function cannot modify its implicit arguments. In the next lesson, we will look at an example program that illustrates these differences.

Question: What is a "const member function"?
Answer: A member function that inspects (rather than mutates) its object.

A const member function is indicated by a const suffix just after the member function's parameter list. Member functions with a const suffix are called "const member functions" or "inspectors." Member functions without a const suffix are called "non-const member functions" or "mutators."

class Test {
public:
  void inspect() const;   // This member promises NOT to change *this
  void mutate();          // This member function might change *this
};

void userCode(Test& changeable, Test const& unchangeable){
  changeable.inspect();   // OK: doesn't change a changeable object
  changeable.mutate();    // OK: changes a changeable object

  unchangeable.inspect(); // OK: doesn't change an unchangeable object
  unchangeable.mutate();  // ERROR: attempt to change unchangeable object
}
The error in unchangeable.mutate() is caught at compile time. There is no runtime space or speed penalty for const. The trailing const on inspect() member function means that the abstract (client-visible) state of the object isn't going to change. This is slightly different from promising that the "raw bits" of the object's struct are not going to change.
C++ compilers are not allowed to take the "bitwise" interpretation unless they can solve the aliasing problem, which normally can not be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn't guarantee that the object won't change; it promises only that the object won't change via that pointer.