Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple question about C++ constant syntax

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!

like image 549
WilliamLou Avatar asked Apr 27 '10 02:04

WilliamLou


People also ask

What is constant in C syntax?

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.

What is the syntax for constant?

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.

What are the 3 constants used in C?

Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.

How many types of constants are allowed C?

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.


1 Answers

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

like image 138
dreamlax Avatar answered Sep 29 '22 09:09

dreamlax