- Reference is how something is passed to a function. You can't used it to create a pointer like C/C++.
- If your function takes a Base, why would you want to cast it? If you function needs a Derived, that is what the parameter should be.
- Also if you pass something other than a Derived, and you try to cast it, the code dies (bad cast) just like a divide by zero.
- See dynamic_cast - MQL4 forum where I pass a pointer by reference, cast a Base to Derived and can avoid the bad cast.
void MyFunc(const Base & obj)
While const is how you should pass them, you can't cast const pointersderive* d = (const derive*)b; 'const' - unexpected token testscr.mq4 67 16
WHRoeder:
- Reference is how something is passed to a function. You can't used it to create a pointer like C/C++.
- If your function takes a Base, why would you want to cast it? If you function needs a Derived, that is what the parameter should be.
- Also if you pass something other than a Derived, and you try to cast it, the code dies (bad cast) just like a divide by zero.
- See dynamic_cast - MQL4 forum where I pass a pointer by reference, cast a Base to Derived and can avoid the bad cast.
- While const is how you should pass them, you can't cast const pointers
2, I want to pass Base for polymorphic. Indeed MyFunc is a virtual function defined in the Base class and overrided by Derived. In my example, MyFunc accepts a Derived object indeed, that's why I want to cast it.
4, The example is about pointer. My more questions: is pointer only used for dynamically allocated objects (new Derived) etc? I put Derived object in an array, not allocating it on heap.
Any detailed explanation or documentation on reference/pointer in MQL, or compare to C++ (I have deep understanding in C++)?
Thanks for your reply.
- If the function is defined in the base then call it, no cast is required; that is the purpose of virtual. As a matter of good programming, all virtual functions should be private.
- Your function does not accept a derive object it accepts a base.
void MyFunc(const Base & obj)
- A pointer can be used for either, but you must assure that the stack object outlives the pointer.
- In C++ the ampersand is both by reference in function calls, and to create pointer. In MQ4 to create a pointer you use GetPointer - MQL4 Documentation
GetPointer solved my problem.
Thank you very much.
Hi wqking, could you provide source code of your solution? Thank you very much!
I believe I found it out:
Derived *derivedObj = (Derived*) GetPointer(baseObj);

You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
As the code above, the obj passed to MyFunc is indeed Derived. So how can I type cast it to Derived?
Also, seems reference '&' can only be used as function parameter? It can't be used to declare local variable?
Thanks