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

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Function-Overloading.html