What the const modifier means after a method declaration

 

Asked a question in private, what does it mean. I've found a helpful example on the forum that helps clarify it.
By the way, if you speak English it's very useful to Google such question in English, not in MQL, but in C++. E.g. like this
http://www.google.com/search?q=const+in+c%2B%2B+after+function&oq=const+in+c%2B%2B&sourceid=chrome&ie=UTF-8
There will be lots of links to pure programming forums, and C++ is quite similar to MQL

I translated the comments into Russian and made some adjustments for MQL compatibility. I am attaching the script below, compile it and everything will become clear.

struct X
{
    void foo() const 
    {
        _x = 42; // ERROR! метод объявлен, как const, не можем менять члены 
        _y = 42; // ERROR! 
    }

    void bar(X& obj) const 
    {
        obj._x = 42; // OK! obj передается по ссылке и не имеет модификатора const
        _x = 42; // ERROR!
    }

    void bar(X const& obj) 
    {
        obj._x = 42; // ERROR! obj передается по ссылке, как const
        obj._y = 42; // ERROR! obj передается по ссылке, как const
        _x = 42; // OK! метод объявлен без const на сонце
    }

    int _x, _y;
};
Files:
TestConst.mq4  2 kb
 
Alexey Volchanskiy:

Asked a question in private what this means. Rushed on the forum to answer it, as I found a useful example that brings clarity.
By the way, if you speak English, it's very useful to Google such question in English, not in MQL, but in C++. E.g. like this
http://www.google.com/search?q=const+in+c%2B%2B+after+function&oq=const+in+c%2B%2B&sourceid=chrome&ie=UTF-8
There will be lots of links to pure programming forums, and C++ is quite similar to MQL

I translated the comments into Russian and made some adjustments for MQL compatibility. I am attaching the script below. Just compile it and everything will become clear.

Doesn't the documentation bring any clarity?

A method with theconstmodifier is called constant and cannot modify the implicit members of its class. Declaration of constant class functions and constant parameters is called const-correctnesscontrol. With this control you can be sure that the compiler will keep track of unchanged values of objects and generate an error at the compilation stage in case of infringement.

Theconstmodifier should be placed after the list of arguments inside the class declaration. Definition outside a class should also include theconst modifier:

An additional argument for using integrity control is that the compiler makes special optimizations, e.g. placing a persistent object in read-only memory.

Astatic function cannot be defined with theconstmodifier, because this modifier guarantees that the members of the instance remain unchanged when such function is called. But, as mentioned above, a static function by definition cannot access non-static class members.

https://www.mql5.com/ru/docs/basis/oop/staticmembers

Moreover, in my opinion, you've presented not the most successful example of making up a structure (methods first, then member data). And, for that matter, it's better to wrap it all in a class rather than a structure, since structures are usually used as a union of data (without methods).

Документация по MQL5: Основы языка / Объектно-ориентированное программирование / Статические члены класса
Документация по MQL5: Основы языка / Объектно-ориентированное программирование / Статические члены класса
  • www.mql5.com
Основы языка / Объектно-ориентированное программирование / Статические члены класса - справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Alexey Kozitsyn:

Doesn't the documentation clarify things?

https://www.mql5.com/ru/docs/basis/oop/staticmembers

And in my opinion, you didn't provide the best example of putting together a structure (methods first, then member data). And, for that matter, it's better to wrap it all in a class rather than a structure, since structures are usually used as a union of data (without methods).

Contains

I remembered it was written somewhere in a doc, but I couldn't find it. I copied an example from stackoverflow. Where to put the data is a personal matter of the programmer, although I put it at the beginning myself. Whether to use structures or classes is up to the programmer )))

 
Alexey Volchanskiy:

Entering

I remembered that it was written somewhere in the doc, but I couldn't find it. I stole a quick example from stackoverflow. It's up to the programmer where to put the data, although I put it at the beginning myself. Whether to use structures or classes is up to the programmer ))))

You may say "a private matter" about many things in such a way. But you are the one who is explaining it to someone and not in person but publicly. And your "private affair" contradicts a good programming style. And the person to whom you are explaining it, and many other users can take it as a good style, which it is not.

And about the person who wanted (or maybe led) the course here, such a "bloop, bloop, bloop" says a lot.

 
Метод с модификатором const is called constant and cannot modify the implicit members of its class.
Which members are explicit, which are implicit?
 
Dmitry Fedoseev:
Which members are explicit, which are implicit?

Apparently, in this context, these are the members that call the method. Or, otherwise, they are the members that can be accessed via this from the method.

 

In C++, this means that a method cannot change class members, except for members declared mutable.

Since in MQL you can hardly expect this, it means that a method cannot change an object in principle.

 
Комбинатор:

In C++, this means that a method cannot change class members, except for members declared mutable.

Since in MQL you can hardly expect this, it means that a method cannot change an object in principle.

A constant method cannot change only the object that called it. But if another object is passed to method without const modifier, it (method) can change it quite successfully.
 
Alexey Kozitsyn:
A constant method cannot change only the object that called it.
Is this an oversight?
 
Alexey Volchanskiy:
Is that a typo?
Explain what you mean by that?
 
Constant method is another example of the proverb "we wanted to do better, but it turned out the same way we always do". I think this is a motto for C++ at all. There is no practical use, but it significantly complicates design of OOP-programs, because you constantly need to control the type of modified object (must be constant as well).