Source:
Declaring a const variable
- General Rule: The 'const' qualifier works on everything on the left of it.
- Convention: If a type T is not a reference or a pointer, a constant variable of type T can be declared by putting 'const' in front of T
Passing reference-to-const v.s. passing pointer-to-const
Taking the pointer to a temporary is not allowed but it is possible to pass a temporary to a function as a reference-to-const:
void foobar(T const&);
foobar( T() ); // Allowed.
Constant/non-constant method and constant/non-constant returned value
class Foo
{
public:
/*
* Modifies m_widget and the user
* may modify the returned widget.
*/
Widget *widget();
/*
* Does not modify m_widget but the
* user may modify the returned widget.
*/
Widget *widget() const;
/*
* Modifies m_widget, but the user
* may not modify the returned widget.
*/
const Widget *cWidget();
/*
* Does not modify m_widget and the user
* may not modify the returned widget.
*/
const Widget *cWidget() const;
private:
Widget *m_widget;
}
- Const method: A method that does not modify the member variables of a class. Calling non-constant methods within a const method is not allowed.
No comments:
Post a Comment