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 non-mutable member variables within the function; the compiler will emit an error. 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 an object; therefore it has no instance whose members it could modify. 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:



Table Of Contents