Previous: Operator Overloading, Up: Overloading Objects [Contents][Index]
Many functions and operators take two or more arguments and the situation can
easily arise where these functions are called with objects of different
classes. It is therefore necessary to determine the precedence of which method
from which class to call when there are mixed objects given to a function or
operator. To do this the superiorto
and inferiorto
functions can
be used
When called from a class constructor, mark the object currently constructed as having a higher precedence than class_name.
More that one such class can be specified in a single call. This function may only be called from a class constructor.
See also: inferiorto.
When called from a class constructor, mark the object currently constructed as having a lower precedence than class_name.
More that one such class can be specified in a single call. This function may only be called from a class constructor.
See also: superiorto.
With the polynomial class, consider the case
2 * polynomial ([1, 0, 1]);
that mixes an object of the class "double"
with an object of the class
"polynomial"
. In this case the return type should be
"polynomial"
and so the superiorto
function is used in the class
constructor. In particular the polynomial class constructor would be modified
to
## -*- texinfo -*- ## @deftypefn {} {} polynomial () ## @deftypefnx {} {} polynomial (@var{a}) ## Create a polynomial object representing the polynomial ## ## @example ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n ## @end example ## ## @noindent ## from a vector of coefficients [a0 a1 a2 @dots{} an]. ## @end deftypefn function p = polynomial (a) if (nargin == 0) p.poly = [0]; p = class (p, "polynomial"); else if (strcmp (class (a), "polynomial")) p = a; elseif (isreal (a) && isvector (a)) p.poly = a(:).'; # force row vector p = class (p, "polynomial"); else error ("@polynomial: A must be a real vector"); endif endif superiorto ("double"); endfunction
Note that user classes always have higher precedence than built-in
Octave types. Thus, marking the polynomial class higher than the
"double"
class is not actually necessary.
When confronted with two objects of equal precedence, Octave will use the method of the object that appears first in the list of arguments.
Previous: Operator Overloading, Up: Overloading Objects [Contents][Index]