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.
- A const member function can be called on both const and non-const objects.
- A non-const member function can only be called by non-const objects.
Code Example
Explanation
Define the classclass MyClass {
public:
void constFunc() const {
cout << " const function." << endl;
}
void nonConstFunc() {
cout << " non-const function." << endl;
}
};
MyClass with two member functions:
- constFunc(): A const member function. It is marked with the const keyword at the end of its declaration.
- nonConstFunc(): A non-const member function.
Main Function:
const MyClass constObj;
MyClass nonConstObj;
Two objects are created:
- constObj: A const object.
- nonConstObj: A non-const object.
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.