Download MetaTrader 5

Typecasting from base to derivative class

To add comments, please log in or register
Bogdan Tenea
202
Bogdan Tenea 2012.03.19 21:39 

"You can use the explicit casting to convert the base class pointers to the pointers of a derived class. But you must be fully confident in the admissibility of such a transformation, because otherwise a critical runtime error will occur and the mql5 program will be stopped."

 Is there any way to check what kind of object type I am using - for example get the class name ? I wish to be able to do this to see I am casting to the right type of object a base class. For example in java you have the "getClass" method :)

dck
70
dck 2012.08.06 17:43  

You are right, a getClass() method would be usefull.

Ex Ovo Omnia
3194
Ex Ovo Omnia 2014.06.11 11:51  

Besides the explicit typecasting there is undocumented implicit typecasting, too.

Considering it is rather unique feature neither used in C++ nor JAVA, I wonder how stable it is. I mean, if I coded using implicit casting, would I get a surprise with subsequent compiler versions?

 The following code compiles, so far.

void OnStart() {
   B* x = new B();
   // compiles OK without explicit typecasting
   A* a = x.getO(); 
   B* b = x.getO();
   C* c = x.getO();
}

class O {
};

class A: public O {
};

class B: public O {
public:
   O* getO() {return new O();}
};

class C: public O {
};
Alain Verleyen
Moderator
31089
Alain Verleyen 2017.04.13 20:45  
Ex Ovo Omnia:

Besides the explicit typecasting there is undocumented implicit typecasting, too.

Considering it is rather unique feature neither used in C++ nor JAVA, I wonder how stable it is. I mean, if I coded using implicit casting, would I get a surprise with subsequent compiler versions?

 The following code compiles, so far.

It compiles but doesn't run, at least in current build (1065/ME1562).

2017.04.13 20:41:42.626    __tests__ EURUSD,M1: incorrect casting of pointers in '__tests__.mq4'

whroeder1
14742
whroeder1 2017.04.14 14:36  
Bogdan Tenea: Is there any way to check what kind of object type I am using
  1. dynamic_cast
  2. But you shouldn't care. The base class should have all the capabilities you need. Object-Oriented Programming
To add comments, please log in or register