Call a function dynamically

To add comments, please log in or register
Patrick Chalindar
981
Patrick Chalindar  

Hi,

do you know if it's possible to call a function dynamically please? I f yes, how?

Example:

Function declaration:

Void myFunction1(){...;...;...;}

Void myFunction2(){...;...;...;}

Void myFunction3(){...;...;...;}

In the code:

for(i=1;i<4;i++)
{
  myFunction+"i()";

}
This example doens't work, but it's the idea I would want to do.


Thanks!!

Alain Verleyen
36153
Alain Verleyen  

Yes and no.

It's possible with pointer to function, but you need to have the same function signature.

Ahmed Soliman
19620
Ahmed Soliman  
Patrick Chalindar:

Hi,

do you know if it's possible to call a function dynamically please? I f yes, how?

Example:

Function declaration:

Void myFunction1(){...;...;...;}

Void myFunction2(){...;...;...;}

Void myFunction3(){...;...;...;}

In the code:

for(i=1;i<4;i++)
{
  myFunction+"i()";

}
This example doens't work, but it's the idea I would want to do.


Thanks!!

No you can not. I wished this feature too but it exists only in PHP.
whroeder1
17940
whroeder1  
  1. When you post code please use the CODE button (Alt-S)! (For large amounts of code, attach it.) Please edit your post.
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. There is no such thing, but you can make one.
    void myFunction1(){...;...;...;}
    
    void myFunction2(){...;...;...;}
    
    void myFunction3(){...;...;...;}
    
    void myFunction(int i){
       switch(i){
       case 1: myFunction1(); break;
       case 2: myFunction2(); break;
       case 3: myFunction3(); break;
       default: PrintFormat(__FUNCTION__" called with %i",i);
       }; // switch
    }
    
    for(i=1;i<4;i++){
      myFunction(i);
    }

Petr Nosek
1287
Petr Nosek  

Patrick Chalindar:

Hi,

do you know if it's possible to call a function dynamically please? I f yes, how?

As @Alain Verleyen said if you have the same function signature it is possible. You can use pointers to function or you can use classes. See an example:

class cParent
  {
public:
   virtual double math(const double a,const double b) {return(0.0);}
  };
class cAdd:public cParent
  {
   virtual double math(const double a,const double b) {return(a+b);}
  };
class cMultiple:public cParent
  {
   virtual double math(const double a,const double b) {return(a*b);}
  };

void OnStart()
  {
   cParent *math[2];
   math[0]=new cAdd();
   math[1]=new cMultiple();
   double a=3.0,b=5.0;
   printf("Addition: %.2f ; Multiplication: %.2f",math[0].math(a,b),math[1].math(a,b));
   // Result: Addition: 8.00 ; Multiplication: 15.00
   delete math[0];
   delete math[1];
  }
Patrick Chalindar
981
Patrick Chalindar  

Thanks for your answers,

structure and classes are somethings about that I had thought, it's helpfull but not exactly that I want to do.

To add comments, please log in or register