The use of const keyword in function definition

 

Hi all,

can anyone, please, explain what is the purpose of using the keyword 'const' in function definition? I have seen this in many places, for example in the CTrade class (see code snippet below) but the MQL5 language reference does not explain this at all.

Thanks in advance,

Rob.

   string            RequestActionDescription()        const;
   ulong             RequestMagic()                    const { return(m_request.magic);             }
   ulong             RequestOrder()                    const { return(m_request.order);             }
   string            RequestSymbol()                   const { return(m_request.symbol);            }
   double            RequestVolume()                   const { return(m_request.volume);            }
 

From MQL5 Reference:

A method with the const modifier is called constant and cannot modify implicit members of its class. Declaration of constant functions of a class and constant parameters is called const-correctness control. Through this control you can be sure that the compiler will ensure the consistency of values of objects and will return an error during compilation if there is something wrong.

You can find more information in the Static members of a Class/Structure section.

 
Alexx:

From MQL5 Reference:

You can find more information in the Static members of a Class/Structure section.

Thanks for that, much appreciated.
 
And you can call this methods for const objects of this class type

class CFoo
  {
public:
   void     f() { };
   void     g() const { }
  };


void func(const CFoo &foo)
  {
   foo.f(); // error, cannot call non const method for const object
   foo.g(); // ok, g() is const method
  }