enforcing that a class method is called instead of an "imported" function with the same name
Show older comments
Hi all,
I have a function called process(arg0, obj) that accepts two arguments. The second can be either a numeric matrix or an object of a custom made class (say, of class MyClass). The latter class has a method called dosomething. Within process(), I have the following code:
import MISC.dosomething;
dosomething(obj);
Where MISC is just a package where I have placed a function called dosomething (this is a normal function, not a method of any object). Obviously, what I want is that, if obj is of class MyClass, the class-associated method dosomething is called while, if obj is anything else but a MyClass object, the function MISC.dosomething is called. However, no matter what, function MISC.something is always called, even if obj is of class MyClass. I find this behavior rather counter-intuitive as I would expect that objects methods have higher preference than imported functions. Is there any way to enforce that MATLAB chooses object methods rather than an imported function that has the same name?
Thanks in advance.
Best,
Germán
Accepted Answer
More Answers (1)
Jan
on 21 Jul 2011
The imported method is known at compile time (the time when the M-file is read and parsed - it is not "compiled" in a stricter definition), while the class of the object is determined at runtime only.
When I read the program, I'm be confused also. So I would not blame the JIT or the Matlab parser, but avoid the IMPORT of functions with ambigious names.
What happens, if you import the functions dynamically:
eval('import MISC.dosomething')
?? Just kidding - increasing the confusion level is not helpful...
1 Comment
German Gomez-Herrero
on 21 Jul 2011
Categories
Find more on Structured Data and XML Documents in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!