Constant objects and member functions |
Basic Concept:
Syntax:
For a member Function:
returnType functionName() const // Constant member function
For an Object:
className const objectName // Constant object
Example program:
A const member function can be called on a const object:
class abc
{
public:
void const_function() const;
void function();
private:
int x;
};
const abc co;
abc o;
co.const_function(); // legal
co.function(); // illegal, can't call regular function on const objecto.const_function(); // legal, can call const function on a regulared objecto.
function(); // legal
Furthermore, it also tells the compiler that the const function should not be changing the state of the object and will catch those problems:
void abc::const_function() const{
x = 3; // illegal, can't modify a member in a const object
}
Constant object can't access non-constant function.
ConversionConversion EmoticonEmoticon