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
{
private:
    int myInt_;
public:
    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:

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


const keyword:
* Syntax
* Const member functions

Table Of Contents
8 Arrays
10 const keyword
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype