Hello!

In one of the answers I saw that the class field is defined as follows:

void(My::*z)( int ); 

Explain, please such a record. When is it used?

  • four
    Pointer to one of the methods of the class My, which takes an argument of type int that returns nothing. - avp
  • I see. Thanks. And this means that a certain function z = & My :: state_2; is assigned to the pointer; And in this place called the state_2 function (this -> * z) (x); Right? Thank you - Pyatak
  • 2
    True, they just called not state_2 , but called the one pointed to by z at the moment. This can be state_1 , state_2 or state_3 . - mega

1 answer 1

When is it used?

Such a field is used in cases where there is some external dependence on the class method. In my example, this dependence on the internal state of the object. Without the "pointer to the method" would still have to enter the additional variable State . But in that case, the logic of the method would not be so obvious.

Here is the same example without z :

 class My{ int State; public: My( void ) : State( 0 ){} void state( int x ){ switch( State ){ case 0: if( x == 1 ){ State = 1; } break; case 1: if( x == 2 ){ State = 2; }else{ State = 1; } break; case 2: if( x == 3 ){ State = 0; } break; } } } 

Obviously, in this version it is much easier to get confused in the numbers of states than in the initial one. For better orientation by code, enum is introduced in such cases:

 class My{ enum{ state_1 = 0, state_2, state_3 }; int State; public: My( void ) : State( state_1 ){} void state( int x ){ switch( State ){ case state_1: if( x == 1 ){ State = state_2; } break; case state_2: if( x == 2 ){ State = state_3; }else{ State = state_1; } break; case 2: if( x == 3 ){ State = state_1; } break; } } } 

But in my opinion, even in this case, the initial version is more profitable to understand.

  • one
    Super! Thanks you. - Pyatak