Const member functions

suggest change

Member functions of a class can be declared const, which tells the compiler and future readers that this function will not modify the object:

class MyClass
    int myInt_;
    int myInt() const { return myInt_; }
    void setMyInt(int myInt) { myInt_ = myInt; }

In a const member function, the this pointer is effectively a const MyClass * instead of a MyClass *. This means that you cannot change any member variables within the function; the compiler will emit a warning. So setMyInt could not be declared const.

You should almost always mark member functions as const when possible. Only const member functions can be called on a const MyClass.

static methods cannot be declared as const. This is because a static method belongs to a class and is not called on object; therefore it can never modify object’s internal variables. So declaring static methods as const would be redundant.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents