Search code examples
c++constantsfunction-qualifier

const parameters in a const member function


I have read about use cases of const and I feel like I have a good understanding of const for the most part. However, I can't seem to figure out why I don't see this more often:

void someFunction(const string& A) const

Where you have a const parameter in a const member function. For some reason, whenever I look up examples and the function is const, the const seems to be stripped off the parameters like this:

void someFunction(string& A) const

However that doesn't seem to stop me from modifying A. Is it considered bad form to have const parameters in a const member function?

What is the reasoning for not keeping the const in the parameters as well if A would not be modified?

EDIT: This is my fault for not clarifying but I understood the difference between adding it before the parameter and adding it after the function. A lot of code I looked at just never combined the two and I was just trying to figure out if there was a reason for that.


Solution

  • void someFunction(const string& A) const
    

    The last const means that the method will not change the state of the object referenced by *this inside it. The first const is saying that the function will not change the state of the argument - and it doesn't have any correlation with the second const, so you may have this:

    void someFunction(string& A) const
    

    In this case function may change state of A argument, but it may not change the state of its object.

    For example (and this is a highly hypothetical example):

    class MyIntArray
    {
     // some magic here in order to implement this array    
    
    public:
     void copy_to_vector(std::vector<int> &v) const
     {
        // copy data from this object into the vector.
        // this will modify the vector, but not the
        // current object.
     }
    
    }
    

    And this is the example where these two are combined:

    class MyOutput
    {
        char prefix;
        // This class contains some char which
        // will be used as prefix to all vectors passed to it
    public:
         MyOutput(char c):prefix(c){}
         void output_to_cout(const std::vector<int> &i) const
         {
            // iterate trough vector (using const_iterator) and output each element
            // prefixed with c - this will not change nor the vector
            // nor the object.
         }
    
    }
    

    Oh, and take a look into this question: Use of 'const' for function parameters