question about function handles in OO
Show older comments
Function handles are not behaving as I expect in an OO project, and I'd like to understand why not.
In brief, I have a class ("clOuter") which has an object of another class ("clInner") as one of its properties. I want to make a function handle to a function of the inner object (a handle that I will then pass elsewhere). But MATLAB doesn't recognize the function handle that I make in what seems to me the obvious way.
Here is a minimal example:
classdef clOuter < handle
properties
inner % outer class has an instance of inner class.
end
methods
function obj = clOuter % Constructor
obj.inner = clInner;
end
end
end
classdef clInner < handle
methods
function obj = clInner % Constructor
end
function result = Add(obj,x,y)
result = x + y;
end
end
end
% Demo script:
outer = clOuter; % Make the outer object. Its constructor makes the inner one.
fn = @outer.inner.Add; % Make a function handle to the inner object's function.
fn(3,2) % Call the function using its handle; this bombs.
% error message: Unrecognized function or variable 'outer.inner.Add'.
In short, why doesn't my function handle 'fn' work in this script? (MATLAB does say fn's class is 'function_handle'.) It's no problem to workaround the error, but I'd like to understand what it is about MATLAB's OO model that precludes making a function handle like this.
Thanks,
Accepted Answer
More Answers (0)
Categories
Find more on Function Handles 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!