If I get a C++ statement as follows:
double getPrice() const;
What doesn const
represent here?
Thanks.
If I get a C++ statement as follows:
double getPrice() const;
What doesn const
represent here?
Thanks.
This is for member functions (in classes or structs). It means that the method won't change the state of the instance it operates on (won't change any member variables for example).
When you call nonstatic member functions, you always call it on some object, right? That object is passed (implicitly) as a parameter. For example, if GetPrice is the method of class X, then it has an implicit parameter of type X&
. Then the method is const, the implicit argument is of type const X
&, therefore the member function cannot change any data member of the object on which it was invoked, UNLESS the data member was declared mutable
.
It signifies that it will not change the members of the class as a side effect.
const
means that getPrice()
won't modify instance fields, except those explicitly declared as mutable
.