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

#### 34.4.1 Function Overloading

Any Octave function can be overloaded, and this allows an object-specific version of a function to be called as needed. A pertinent example for the polynomial class might be to overload the `polyval` function.

    function [y, dy] = polyval (p, varargin)

      if (nargout > 1)
        [y, dy] = polyval (fliplr (p.poly), varargin{:});
      else
        y = polyval (fliplr (p.poly), varargin{:});
      endif

    endfunction

This function just hands off the work to the normal Octave `polyval` function. Another interesting example of an overloaded function for the polynomial class is the `plot` function.

    function h = plot (p, varargin)

      n = 128;
      rmax = max (abs (roots (p.poly)));
      x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
      if (nargout > 0)
        h = plot (x, polyval (p, x), varargin{:});
      else
        plot (x, polyval (p, x), varargin{:});
      endif

    endfunction

which allows polynomials to be plotted in the domain near the region of the roots of the polynomial.

Functions that are of particular interest for overloading are the class conversion functions such as `double`. Overloading these functions allows the `cast` function to work with a user class. It can also aid in the use of a class object with methods and functions from other classes since the object can be transformed to the requisite input form for the new function. An example `double` function for the polynomial class might look like

    function a = double (p)
      a = p.poly;
    endfunction