Friday, February 19, 2016

C++ : const at the end of function declaration

class User
{
    public:
        User();
        User(std::string name);
        void doSomething() const;

    protected:
        std::string m_name;
};


In .cpp:

void User::doSomething() const
{
    // code
}

The const keyword indicates that *this (the object) is const on the method call. This declaration tells you that the object will not be modified within this function (in the example above, doSomething() cannot modify m_name).

Note : In practice, this notation is just a promise that can be violated by the function (not advised though).

0 comments:

Post a Comment