const-correctness - initialization of variables within class



  • Does anyone see a problem here in const-correctness?

    class iterator {
        private:
            Node<Pair>* _ptr/* = nullptr */;
            MtmMap<ValueType, KeyType, CompareFunction>* _map_ptr;
        public:
            iterator(Node<Pair>* ptr, const MtmMap<ValueType, KeyType, CompareFunction> * mtm_ptr)
                : _ptr(ptr), _map_ptr(mtm_ptr){ }
    

    Compiler screams:

    cannot convert from 'const MtmMap *' to 'MtmMap *'

    And that's probably why:

    'mtm:



  • You can't assign the index value to a constant object to a non-constant object.

    So the compiler tells you right about the error in the designer.

    iterator(Node<Pair>* ptr, const MtmMap<ValueType, KeyType, CompareFunction> * mtm_ptr)
                        : _ptr(ptr), _map_ptr(mtm_ptr){ }
    

    because the parameter mtm_ptr You havere an index to constant object.

    const MtmMap<ValueType, KeyType, CompareFunction> * mtm_ptr
    

    a Class data member _map_ptr - it's a non-constant object indicator.

    MtmMap<ValueType, KeyType, CompareFunction>* _map_ptr;
    

    Therefore, initialization _ptr(ptr) Not correct.

    This is a more simplified demonstration example

    int main()
    {
        const int x = 10;
        const int *cp = &x;
        int *p = cp;
    }
    

    The compiler will give a message like this.

    prog.cc: In function 'int main()':
    prog.cc:5:14: error: invalid conversion from 'const int*' to 'int*' [-fpermissive]
         int *p = cp;
                  ^
    

    Since otherwise, you are given the opportunity to change the facility through a non-constant object indicator, which in general leads to an uncertain programme behaviour. This non-return is therefore prohibited by C+++.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2