C++ Constants

  1. What is const

    Const is keyword used do declare variable that cannot be changed.

  2. Const with different contexts

    Const can be used in different places and each of them mean something different. For example:

    • Const Variables
      You declare that variable cannot be changed using const keyword

      const int max_size = 5;
    • Const with pointers
      If const keyword is in front of the * it means that you can't modify contents of pointer, the value at memory adress it points to but you can modify memory adress that it points to.

      int max_size = 5;
      int min_size = 0;
      const int* size = &max_size;
       
      *size = 3; // you cannot do that
      size = &min_size; // you can do that

      If const keyword is after the * it means that you can modify contents of pointer but not the adress that it points to.

          int max_size = 5;
          int min_size = 0;
          int* const size = &max_size;
       
          *size = 3; // you can do that
          size = &min_size; // you cannot do that
    • Const with classes
      If you write const in methods you can't change any values in this method.

      class Entity{
      private:
         int m_X, m_Y;
       
      public:
         int getX() const{
             m_X = 2; // you cant do that
             return m_X;
         }
      };

      But if you need to change something you can use mutable keyword

      class Entity{
      private:
        int m_X, m_Y;
        mutable int var;
       
      public:
        int getX() const{
            m_X = 2; // you cant do that
            var = 2; // you can do that because of mutable keyword
            return m_X;
        }
      };