PDA

View Full Version : Type casting reference to object to derived class?



Bradleyzoot
02-06-2016,
class Base
{
};

class Derived : public Base
{
public:
void MyFunc(const Base & obj)
{
// how to type cast obj to Derived?
}
};


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

Brandondert
02-07-2016,
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 (https://forum.mql4.com/62793#1022400) 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 pointers
derive* d = (const derive*)b;
'const' - unexpected token testscr.mq4 67 16

BrandonLig
02-08-2016,
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.

Brandonot
02-08-2016,
Hi wqking, could you provide source code of your solution? Thank you very much!
GetPointer solved my problem.
Thank you very much.

craze
02-11-2016,
I believe I found it out:
Derived *derivedObj = (Derived*) GetPointer(baseObj);