Here is some code copied from Thinking in C++ Vol1 Chapter 10.
#include <iostream>
using namespace std;
int x = 100;
class WithStatic {
static int x;
static int y;
public:
void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "WithStatic::y = " << y << endl;
}
};
what's the meaning of const for the function print()? Thanks!
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.
Syntax ¶ Constants can be defined using the const keyword, or by using the define()-function. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.
Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.
An integer constant can be either Decimal, Hexa Decimal or Octal. See the table below to understand how these 3 different constants are defined in C.
I've heard this described previously as “a method that does not logically change the object”. It means that by calling this method the caller can expect the object’s state to remain the same after the method returns. Effectively, the this
pointer becomes a constant pointer to a constant instance of that class, so member variables cannot be altered. The exception to this rule is if member variables are declared with mutable
. If a class has mutable
member variables, these can be modified by both non-const and const methods. Also, non-const methods cannot be called from within a const method.
Some people use mutable
member variables to cache results of timely computations. In theory, the state of the object does not change (i.e. the only effect is that subsequent calls are quicker, but they produce the same results given the same input).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With