2

If I get a C++ statement as follows:

double getPrice() const;

What doesn const represent here?

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

4 Answers4

7

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).

PeterK
  • 6,287
  • 5
  • 50
  • 86
3

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.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
2

It signifies that it will not change the members of the class as a side effect.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

const means that getPrice() won't modify instance fields, except those explicitly declared as mutable.

Trinidad
  • 2,756
  • 2
  • 25
  • 43
  • A binary dump is not guaranteed to be the same before and after. The method is permitted to change members declared mutable. – Alex Deem Feb 24 '11 at 14:27