const keyword

The const declaration creates a read-only reference to a value.

We can use it in C, C++, JavaScript and Julia.

In CS247, we saw how there are 2 types of const:

  1. Physical constness is about a particular object’s implementation. Compiler guarantees this for const objects/const refs. Ensures the fields won’t change.
  2. Logical constness asks not only for the fields to be immutable, but also that the memory associated with the representation of the ADT doesn’t change.

Logical constness is much stronger. There are parallels about physical copies and logical copies, see Shallow Copy and Deep Copy.

Resources

Different Types of Const

  1. Constant variables:
const int MAX_VALUE = 100; 
  1. Constant function parameters:
void printNumber(const int num) { std::cout << num << std::endl; };
  1. Constant member functions in classes
class Circle {
    double radius;
 
public:
    double getArea() const {
        // The member function does not modify any member variables
        return 3.14 * radius * radius;
    }
};
  1. Constant return value (though in this example not useful)
const int addFive(int num) { return num + 5 };

Notice the difference

There is a difference depending on where you put the const keyword.

Taking the const pledge(aka assuring const correctness)

This means that you are promising not to change any of the subparts of the object

  • For subparts that are objects (i.e., not ptrs), the meaning is obvious: You can’t change the sub-parts!
  • NOTE: If the subpart is a pointer, you can’t change the pointer to point to a different object
    • However, you are allowed to change the subparts of any object you point to, including calling non-const methods

const pointers

int* a;             // Pointer to int
const int* a;       // Pointer to const int
int* const a;       // Const pointer to int
const int* const a; // Const pointer to const int

https://www.internalpointers.com/post/constant-pointers-vs-pointer-constants-c-and-c