Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - What does const represent here? [duplicate]

Tags:

c++

constants

If I get a C++ statement as follows:

double getPrice() const;

What doesn const represent here?

Thanks.

like image 602
Simplicity Avatar asked Jun 12 '26 14:06

Simplicity


2 Answers

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

like image 141
PeterK Avatar answered Jun 15 '26 05:06

PeterK


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.

like image 21
Armen Tsirunyan Avatar answered Jun 15 '26 05:06

Armen Tsirunyan