How to use const keywords with pointers?


  • Banned

    Hi, i am looking for some example code that help me to use const keyword with pointers. While working on C++projects I have faced many issues related with C++ questions & answers, so I am hoping for valuable suggestions & great support from the online community.


  • Moderators

    Hi @kyleflores, and welcome to the Qt Dev Net!

    Google is your friend. I just typed "C++ const" and immediately found many helpful articles, including https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const


  • Qt Champions 2016

    This article doesn't cover the multidimensional case ;p

    int * z = nullptr;
    const int * const * const p = &z;
    


  • Hello,
    Seems more appropriate to ask this question in a site dedicated to standard C++ questions (i.e. http://stackoverflow.com), rather than on the Qt-specific forum.



  • I'm not sure if this is the answer you're looking for, but:

    The rule of thumb is: what's to the left of the word const is constant (i.e. you're not allowed to change it), unless there's nothing to the left, than whatever is to the right of it is constant.

    char* const pc //the pointer is constant, but the value of what it points to is not
    char const *pc //the value pointed to (the character) is constant, but the pointer is not (i.e. its memory address)
    const char *pc //again, the value pointed to is constant, but the pointer is not
    const char* const pc //both the value and the pointer are constant
    

    Furthermore, if the word const appears after a function declaration, it signifies that no class members will be altered in the function.

    void MyClass::fun(char *pc) const { //All MyClass members are const
        //do stuff
    }
    
    Additionally, the keyword mutable exists so you can make something exempt from the rule above, to make it explicitly not const.
    
    class MyClass {
        public:
            //stuff
            OtherClass get_other_class() const {
                oc.init();
                oc_initialized = true; //I'm allowed to do this, even though this function is const
                return oc;
            }
        private:
            OtherClass oc;
            mutable bool oc_initialized {false};
    }
    


  • Hi, I think you should come and take a look at https://www.youtube.com/watch?v=Y1KOuFYtTF4&index=4&list=WL, it's very useful for using const keyword in C++.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.