All are from C++ faqs
The compiler won't allow a const member function to change *this or to invoke a non-const member function for this object:
class Stack {If Fred is some type, then
public:
int pop(); //Mutator
int numElems() const; //Inspector
private:
int element;
};
int Stack::numElems() const
{
++element; // Error
pop(); // Error: pop is not const function
return 1;
};
void sample(const Stack *s)
{
s->numElems();// OK: A const Stack can be inspected
s->pop(); // Error: A const Stack cannot be mutated
}
Fred* is a pointer to a Fred (the * is pronounced "pointer to a").
const Fred* is a pointer to a Fred that cannot be changed via that pointer.
Fred* const is a const pointer to a Fred. The Fred object can be changed via the pointer, but the pointer itself cannot be changed.
const Fred* const is a const pointer to a Fred that cannot be changed via that pointer.
References are similar: read them right to left.
Fred& is a reference to a Fred (the & is pronounced "reference to a").
const Fred& is a reference to a Fred that cannot be changed via that reference
Note that Fred& const and const Fred& const are not included in the second list. This is because references are inherently immutable: you can never rebind the reference so that it refers to a different object.
No comments:
Post a Comment