a common practice in oo programming is to call
the method of the parent class in the overloaded
method of it's derived class and add some
functionality to this overloaded method.
Consider the following to classes:
@class_a
--------
function obj = class_a ()
obj.foo = [];
obj = class (obj, 'class_a');
function func(obj)
print(obj);
function print(obj)
disp('Hello, I''m Class A');
@class_b
--------
function obj = class_b ()
obj.foo = [];
obj = class (obj, 'class_b', class_a);
function func(obj)
% call print from parent
print(obj.class_a);
% call my own print method
print(obj);
function print(obj)
disp('Hello, I''m Class B');
The result is:
>> b=class_b;
>> func(b);
Hello, I'm Class A
Hello, I'm Class B
and should be:
Hello, I'm Class B
Hello, I'm Class B
I.e. the method 'func' of 'class_a' should call
the method 'print' of 'class_b' because it is
overloaded. This is not the case because inheritance
in Matlab OOP is a conglomeration of inheritance and
aggregation: to access the attributes of 'class_a'
you have to write obj.class_a that means you get
an object of type 'class_a'!
Does anybody has a solution to get the correct behavior
like usual OO languages?
Peter
in fact, you can do this is C++, and I did do this
a while back and it took NuMega's debugger to tell
me that I was "chopping off the bottom" of my object
since I was "casting by value."
class_a A;
class_b B;
clase_a C = (class_A) B; %cast by value. (lose vptr table)
if you want to cast by reference, i believe that this
does the trick:
obj = feval('@class_a/print', obj);
hence, if @class_a/print() called func(), it would
properly dispatch to @class_b/func().
if you "chop off the object," then if func() was called
in @class_a/print(), then MATLAB would generate an error like:
no method found
hope this helps.
BTW: when you call feval('@class_a/print',obj) and class_a doesnt
have a print() method, they you get an error even if class_a
has a parent that implements method print().
the code that i wrote did this:
invoke_parentmethod(obj,'methodname', args...)
and it does:
%this code implements a custom form of dispatching:
parent = getparent(obj);
while ~isempty(parent)
if exist([parent '/' methodname],'file')
varargout = feval([parent '/' methodname], varargin{3:end});
return;
end;
parent = getparent(obj);
end;
error(['method ' methodname 'is not implemented']);
this is "almost correct" code since the syntax is bound to be
messed up.
the getparent() function for 'class_b' would return '@class_a',
for example.
i wouldnt really call obj.class_a aggregation because MATLAB
allows multiple inheritence. thus, if it just had "super"
like Java, you couldnt access all of your parents. by
allowing obj.class_a you can select the parent you want to
deal with! (not everyone is that lucky!)
this is long and complex, so ill stop!