What the const modifier means after a method declaration - page 6

 
Constant methods
Constant methods are distinguished by the fact that they don't change the values of their class fields. Let's look at an example called CONSTFU:
// constfu.cpp
// применение константных методов
class aClass
{
private:
    int alpha;
public:
    void nonFunc()    // неконстантный метод
    { 
        alpha = 99;
    }      // корректно
    void conFunc()const   // константный метод
    { 
        alpha = 99;
    }    // ошибка: нельзя изменить значение поля
};

A normal nonFunc() method can change the value of the alpha field, but a constant method conFunc() cannot. If an attempt is made to change the alpha field, the compiler will report an error.
To make a function a constant, the const keyword must be specified after the function prototype, but before the beginning of the function body. If the function declaration and definition are separated, the const modifier must be specified twice - both in the function declaration and in its definition. It makes sense to make those methods, which only read data from the class field, constant, because they don't need to change the values of the class object fields.

The use of constant functions helps the compiler to detect errors and also tells the reader of the listing that the function does not change the values of the object fields. Constant functions can be used to create and use constant objects, as we'll see later.

An example of the Distance class

In order not to include many innovations in a single program, we have so far not used constant methods in our examples. However, there are quite a few situations where using constant methods would be useful. For example, the showdist() method of the Distance class, which repeatedly appears in our examples, should have been made constant because it doesn't (and shouldn't!) change the fields of the object for which it is called. It is only intended to display the current values of the fields on the screen.

...

taken from p. 250, Lafauré R. - Object-Oriented Programming in C++ (4th ed.) 2004

 
Dmitry Fedoseev:

This is what is meant, because in this context, type is not being talked about. "Own class" is obviously its own instance (i.e. object).

The_x member belongs to the same class as the bar method.

C obj._x - here the _x member is in a foreign class obj.

It seems acceptable to me to talk about a class rather than an instance, because it's obvious that _x belongs to our class, which we write, and obj.x to the foreign class, which we handle.

Speaking of OOP terminology, the whole terminology here is a bit of that (or even a lot).

Dmitry, do you understand that if you speak that way, those who will start to get acquainted with OOP with such terminology for the first time will go crazy!

That's what you mean because we're not talking about a type in this context. "Its class" is obviously its own instance (i.e. object).

It's probably obvious to you. I'm reading and wondering how a member _x can belong to a class if the class is an instruction, an abstraction, as you yourself said:

Forum on trading, automated trading systems and strategy testing

What does const modifier after method declaration mean?

Dmitry Fedoseev, 2016.02.01 19:06

How can an object call a method? A method can be called from a function or from another method.

It's not just a class method that is called, but a method of a specific object. The class itself is an abstraction.

C obj._x - here the member _x is in an extraneous class obj.

Do you seriously not understand the difference between a class and an instance of a class!? You can't say that, by no means, because it will cause the reader's brain to explode, and he will think that the object which called the method and the obj object are instances of different classes, although they are instances of one class (in the example you cited).

If we talk about OOP terminology, all terminology here is a bit of that (or even a lot).

Terminology is "a bit of a thing" when you don't understand what you're dealing with. You just need to clearly understand what a class (instruction) is and what an object (instance) of a class is. And then a lot of problems will disappear by themselves. Obviously, I will not be able to change your mind, so I see no point in continuing the discussion on this subject. It's a pity.
 
unreal:
Constant methods
Constant methods are distinguished by the fact that they don't change the values of their class fields. Let's look at an example called CONSTFU:
// constfu.cpp
// применение константных методов
class aClass
{
private:
    int alpha;
public:
    void nonFunc()    // неконстантный метод
    { 
        alpha = 99;
    }      // корректно
    void conFunc()const   // константный метод
    { 
        alpha = 99;
    }    // ошибка: нельзя изменить значение поля
};

A normal nonFunc() method can change the value of the alpha field, but a constant method conFunc() cannot. If an attempt is made to change the alpha field, the compiler will report an error.
To make a function a constant, the const keyword must be specified after the function prototype, but before the beginning of the function body. If the function declaration and definition are separated, the const modifier must be specified twice - both in the function declaration and in its definition. It makes sense to make those methods, which only read data from the class field, constant, because they don't need to change the values of the class object fields.

The use of constant functions helps the compiler to detect errors and also tells the reader of the listing that the function does not change the values of the object fields. Constant functions can be used to create and use constant objects, as we'll see later.

An example of the Distance class

In order not to include many innovations in a single program, we have so far not used constant methods in our examples. However, there are quite a few situations where using constant methods would be useful. For example, the showdist() method of the Distance class, which repeatedly appears in our examples, should have been made constant because it doesn't (and shouldn't!) change the fields of the object for which it is called. It is only intended to display the current values of the fields on the screen.

...

taken from p. 250, Lafauré R. - Object-Oriented Programming in C++ (4th ed.) 2004

But what order will be in your mind if even in a book on OOP they write either right or wrong. Although, perhaps, it's the translation.
 
Alexey Kozitsyn:

Dmitry, do you understand that if you talk like this, those who start to get acquainted with OOP with such terminology for the first time will go crazy?

It's probably obvious to you. I'm reading and thinking how a member _x can belong to a class, if a class is an instruction, an abstraction, as you said yourself:

You seriously don't understand the difference between a class and an instance of a class!? You can't say that, by no means, because it will cause a brain explosion in the reader and he will think that the object which called the method and the obj object are instances of different classes, although they are instances of the same class (in the example you gave).

Terminology is then "a bit of that" when you don't understand what you're dealing with. You just need to understand clearly what a class (instruction) is and what an object (instance) of a class is. And then a lot of problems will disappear by themselves. Obviously, I will not be able to change your mind, so I see no point in continuing the discussion on this subject. It's a pity.

Why should you change my mind? Change your mind about what? Everything is fine with me. The first post of this thread was enough for me to have a complete conflict-free understanding.

Also note that it was you who wrote that the reference would be enough to understand. So it is not clear at all what you are arguing about?

ps. Don't attribute a bunch of your own delusions to me.

 
George Merts:

Personally, I always understood const-methods as methods which cannot change class variables.

I've used them very rarely, because I've often encountered a situation where a method redefinition requires to change something, while the base method is constant (it was already mentioned here).

Static methods are used extensively. In almost any complex class. Usually these are "serving" additional methods that do not require access to the class variables.

In addition, for constants like "number of seconds in a day", I try to use a static const construct instead of #define. In this case, declaration and initialization of such constant are in different places, but the type control occurs and it helps me out more than once.

The same thing I rarely use. In fact, I started the topic because one of this forum participants asked me in a private message why I needed them.
 
George Merts:

Personally, I always understood const-methods as methods which cannot change class variables.

I've used them very rarely, because more than once I've come across a situation where a method override needs to change something, and the base method is constant (it's already been mentioned here).

You do NOT use them for that reason, and I do use them for that reason:

zaskok3:

For me, using const and static greatly increases readability/understanding of my own code. And allows you to often catch bugs or flaws in your own architecture early on in its implementation.


I write everything only for myself. And it would seem that I won't change some data I shouldn't anyway. But the desire to protect myself from my own stupidity makes me rivet OOP-architecture in such a way, that only what must be accessible to change. The rest is not. And here const + inheritance types are of great help. I recommend it.
 

Kind people help with compiling EA very please, I'm not good at programming.

This is the error I get when compiling 'delete' - name expected

The error in the code is highlighted in red

void delete(int type){

if(OrdersTotal()>0){

for(i=OrdersTotal()-1;i>=0;i--){

OrderSelect(i,SELECT_BY_POS,MODE_TRADES);

if(type!=6 && type!=7 && type!=8)if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==type)OrderDelete(OrderTicket();

if(type==6)if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUYSTOP || OrderType()==OP_SELLSTOP || OrderType()==OP_BUYLIMIT || OrderType()==OP_SELLLIMIT)OrderDelete(OrderTicket());

if(type==7)if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_BUYSTOP || OrderType()==OP_BUYLIMIT)OrderDelete(OrderTicket());

if(type==8)if(OrderSymbol()==Symbol() && OrderMagicNumber()==magic && OrderType()==OP_SELLSTOP || OrderType()==OP_SELLLIMIT)OrderDelete(OrderTicket());

}

}

}


Here's another error '(' - object pointer expected

if(oppositedelete){delete(OP_SELLSTOP);delete(OP_SELLLIMIT);}

And here '}' - not all control paths return a value

int countglobal(){

int cnt=0;

if(OrdersTotal()>0){

for(i=OrdersTotal()-1;i>=0;i--){

OrderSelect(i,SELECT_BY_POS,MODE_TRADES);

cnt++;

}

return(cnt);

}

}

 
zaskok3:

You do NOT use them for this reason, and I do use them for this reason:

I agree that the const specifier is useful when reading and understanding long written functions. But restricting access to variables seems to me to make more sense by declaring them in different private-protected-public sections (I personally never declare variables as public, only methods).

It's hard for me to think of a situation where an internal class variable should not be modified in descendants.

 
Anton Razmyslov:

Kind people help with EA compilation very please, not good at programming.

And in the logic? Why clutter up a non-profile topic with questions like this?
 

By the way, nobody wrote that Const modifier not only does not allow to change data inside own class, but even to address non-constant methods. A simple example: there is a position class, we need to sort the list of positions by profit. The profit is calculated by the request:

class CPosition : public CObject
{
private:
   double m_profit;
   void CalculateProfit()
   {
      m_profit = 31337;
   }
public:
   CPosition(void) : m_profit(0.0)
   {
   }
   double Profit(void)const
   {
      if(m_profit == 0.0)
         CalculateProfit(); // <- Константный метод вызывает блок рассчета и вызывает ошибку
      return m_profit;
   }
   virtual int Compare(const CObject *node,const int mode=0) const
   {
      const CPosition* pos = node;
      if(pos.Profit() > Profit())
         return 1;
      else if(pos.Profit() < Profit())
         return -1;
      return 0;
   }
};

This code will cause an error because although the Profit method is constant, it refers to the non-constant method CalcultaeProfit if profit has not yet been calculated.

Note that the Profit method itself is absolutely safe: it guarantees that the value it returns is not empty. However, the constant method requires to abandon behind-the-scenes calculations and high code security in favour of some out-of-the-box constructions which do not know what and why they limit.

Reason: