C++ class, const member function

In C++, a const member function is a member function that does not modify the state of the object on which it is called. Within a const member function, you cannot change any member variables of the object.

Code Example


Explanation

Define the class
class MyClass {
public:
    void constFunc() const {
        cout << "  const function." << endl;
    }
    void nonConstFunc() {
        cout << "  non-const function." << endl;
    }
};

MyClass with two member functions:


Main Function:
const MyClass constObj;
MyClass nonConstObj;

Two objects are created:


Calling the const Member Function:
constObj.constFunc();
nonConstObj.constFunc();

Since constFunc() is a const member function, it can be called on both const and non-const objects.


Calling the Non-const Member Function:
// constObj.nonConstFunc(); // this won't work
nonConstObj.nonConstFunc();

Since nonConstFunc() is a non-const member function, it can only be called on non-const objects. Attempting to call the nonConstFunc() function on constObj will result in compilation error.


Conclusion

const member functions are a valuable tool in C++ for ensuring that certain operations do not modify the state of an object. They provide a guarantee to the caller that the function will not alter the object and can be called on both const and non-const objects. Non-const member functions, on the other hand, can modify the object's state and can only be called on non-const objects.