Statement const at the end of function in C++ and const before argument in method

Asked

Viewed 3,427 times

4

I came across this piece of code in a material:

class Foo 
{
public:
int Bar(int arg1) const //<-- qual função do const aqui?
{
    // código a ser implementado aqui
}
};

[1] Like the const affects this method statement Bar ?

[2] What is the difference between these statements?

const int * ptrInt1;
int const * ptrInt2;

[3] The method with const in the argument, it is for that parameter forced to be read-only in the code implementation?

int Foo (const int Bar) //<-- const antes de argumento na função
{
   // código a ser implementado aqui
}

1 answer

5


  1. With this type modifier you make it clear to the programmer and compiler that the object will not be modified. Members who keep status will not be changed by this method. It is an important protection in many cases where you do not want to allow members to be changed, except by using the keyword mutable.

    class C { //exemplo da Wikipedia
        int i;
        public:
            int Get() const {
                return i;
            }
            void Set(int j) {
                i = j;
            }
        };
    
        void Foo(C& nonConstC, const C& constC) {
            int y = nonConstC.Get(); // Ok
            int x = constC.Get();    // Ok: Get() é const
    
            nonConstC.Set(10); // Ok: nonConstC é modificável
            constC.Set(10);    // Erro! Set() permite modificar o objeto e constC é um objeto constante
        }
    }
    

I put in the Github for future reference.

  1. These two forms are equivalent, there is no semantic difference, only syntactic. But there can be when the const is in other places. Only the const initial can be reversed in its position. It is possible to use const to the pointer and it needs to always come later to not create ambiguity.

    Position indicates who is constant, content or pointer:

     int * - ponteiro para int
     int const * - ponteiro para um int constante
     int * const - ponteiro constante para um int
     int const * const - ponteiro constante para um int constante
    

    You should already know that the statement in C and C++ is backwards.

    By constant pointer understand that you cannot change the value of the variable (point to another object) but you can change the content pointed by it, unless it has also been declared constant.

  2. You got it right, but in this form there is not much advantage. This means the value of Bar cannot be changed within this function. It has the advantage of making this clear and avoiding changing this value mistakenly. But the effect is just local, easy to control.

    This is most important when a parameter receives values by reference or is a form of pointer, after all, changing the parameter will affect the value of the argument used in the call. This is a side effect and has consequences. In general one should avoid changing parameters that can generate side effects as much as possible. Of course, there are several cases where it is necessary to allow the argument to be changed, which is precisely the desired effect.

The call const correctness has a number of holes and one should take great care with their use. These are simplifications of explanation. Of course if you want to better understand each use you should look for documentation or open more specific questions about each aspect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.