Previous: Operator Overloading, Up: Overloading Objects [Contents][Index]

#### 34.4.3 Precedence of Objects

Many functions and operators take two or more arguments and so the case can easily arise that these functions are called with objects of different classes. It is therefore necessary to determine the precedence of which method of 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

Built-in Function: superiorto (class_name, …)

  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.

Built-in Function: inferiorto (class_name, …)

  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.

For example with our 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 we like to ensure that the return type of the above is of the type `"polynomial"` and so we use the `superiorto` function in the class constructor. In particular our polynomial class constructor would be modified to be

    ## -*- texinfo -*-
    ## @deftypefn  {Function File} {} polynomial ()
    ## @deftypefnx {Function File} {} 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");
      elseif (nargin == 1)
        if (strcmp (class (a), "polynomial"))
          p = a;
        elseif (isvector (a) && isreal (a))
          p.poly = a(:).';
          p = class (p, "polynomial");
        else
          error ("polynomial: expecting real vector");
        endif
      else
        print_usage ();
      endif
      superiorto ("double");
    endfunction

Note that user classes always have higher precedence than built-in Octave types. So in fact marking our polynomial class higher than the `"double"` class is in fact not necessary.

When faced with two objects that have the same precedence, Octave will use the method of the object that appears first on the list of arguments.

Previous: Operator Overloading, Up: Overloading Objects [Contents][Index]